更改字典中键的名称

如何更改Python字典中条目的键?

606073 次浏览

只需2步即可轻松完成:

dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]

或者一步:

dictionary[new_key] = dictionary.pop(old_key)

如果dictionary[old_key]未定义,将引发KeyError。注意,这个删除dictionary[old_key]

>>> dictionary = { 1: 'one', 2:'two', 3:'three' }
>>> dictionary['ONE'] = dictionary.pop(1)
>>> dictionary
{2: 'two', 3: 'three', 'ONE': 'one'}
>>> dictionary['ONE'] = dictionary.pop(1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 1

您可以将相同的值与许多键相关联,或者只是删除一个键并重新添加具有相同值的新键。

例如,如果你有键->值:

red->1
blue->2
green->4

没有理由不能添加purple->2或删除red->1并添加orange->1

没有直接的方法做到这一点,但你可以删除然后分配

d = {1:2,3:4}


d[newKey] = d[1]
del d[1]

或者做大量的键改变:

d = dict((changeKey(k), v) for k, v in d.items())

流行乐队'fresh

>>>a = {1:2, 3:4}
>>>a[5] = a.pop(1)
>>>a
{3: 4, 5: 2}
>>>

如果你想更改所有的键:

d = {'x':1, 'y':2, 'z':3}
d1 = {'x':'a', 'y':'b', 'z':'c'}


In [10]: dict((d1[key], value) for (key, value) in d.items())
Out[10]: {'a': 1, 'b': 2, 'c': 3}

如果你想改变单键:

.

.

.

因为键是字典用来查找值的,所以实际上不能更改它们。您可以做的最接近的事情是保存与旧键相关联的值,删除它,然后使用替换键和保存的值添加一个新条目。其他几个答案说明了实现这一目标的不同方式。

我还没有看到确切的答案:

dict['key'] = value
你甚至可以对对象属性这样做。

将它们放入字典
dict = vars(obj)

然后你可以像操作字典一样操作对象属性:

dict['attribute'] = value
在python 2.7及更高版本中,你可以使用字典理解: 这是我在使用DictReader读取CSV时遇到的一个例子。用户已经为所有列名添加了':'

# EYZ0

在键中去掉后面的':':

# EYZ0

如果你有一个复杂的字典,这意味着字典中有一个字典或列表:

myDict = {1:"one",2:{3:"three",4:"four"}}
myDict[2][5] = myDict[2].pop(4)
print myDict


Output
{1: 'one', 2: {3: 'three', 5: 'four'}}

以防一次性更改所有键。 这里我阻塞键。

a = {'making' : 1, 'jumping' : 2, 'climbing' : 1, 'running' : 2}
b = {ps.stem(w) : a[w] for w in a.keys()}
print(b)
>>> {'climb': 1, 'jump': 2, 'make': 1, 'run': 2} #output

转换字典中的所有键

假设这是你的字典:

>>> sample = {'person-id': '3', 'person-name': 'Bob'}

将示例字典键中的所有破折号转换为下划线:

>>> sample = {key.replace('-', '_'): sample.pop(key) for key in sample.keys()}
>>> sample
>>> {'person_id': '3', 'person_name': 'Bob'}
d = {1:2,3:4}

假设我们想要改变列表元素p=['a', 'b']的键值。 下面的代码将完成:

d=dict(zip(p,list(d.values())))

我们得到

{'a': 2, 'b': 4}

这个函数获得一个字典,另一个字典指定如何重命名键;它返回一个新的字典,带有重命名的键:

def rekey(inp_dict, keys_replace):
return {keys_replace.get(k, k): v for k, v in inp_dict.items()}

测试:

def test_rekey():
assert rekey({'a': 1, "b": 2, "c": 3}, {"b": "beta"}) == {'a': 1, "beta": 2, "c": 3}

方法,如果有人想替换多级字典中出现的所有键。

函数检查字典是否有特定的键,然后遍历子字典并递归调用该函数:

def update_keys(old_key,new_key,d):
if isinstance(d,dict):
if old_key in d:
d[new_key] = d[old_key]
del d[old_key]
for key in d:
updateKey(old_key,new_key,d[key])


update_keys('old','new',dictionary)

这将小写你所有的字典键。即使你有嵌套的字典或列表。您可以执行类似的操作来应用其他转换。

def lowercase_keys(obj):
if isinstance(obj, dict):
obj = {key.lower(): value for key, value in obj.items()}
for key, value in obj.items():
if isinstance(value, list):
for idx, item in enumerate(value):
value[idx] = lowercase_keys(item)
obj[key] = lowercase_keys(value)
return obj
json_str = {"FOO": "BAR", "BAR": 123, "EMB_LIST": [{"FOO": "bar", "Bar": 123}, {"FOO": "bar", "Bar": 123}], "EMB_DICT": {"FOO": "BAR", "BAR": 123, "EMB_LIST": [{"FOO": "bar", "Bar": 123}, {"FOO": "bar", "Bar": 123}]}}


lowercase_keys(json_str)




Out[0]: {'foo': 'BAR',
'bar': 123,
'emb_list': [{'foo': 'bar', 'bar': 123}, {'foo': 'bar', 'bar': 123}],
'emb_dict': {'foo': 'BAR',
'bar': 123,
'emb_list': [{'foo': 'bar', 'bar': 123}, {'foo': 'bar', 'bar': 123}]}}

完整解决方案的示例

声明一个json文件,其中包含你想要的映射

{
"old_key_name": "new_key_name",
"old_key_name_2": "new_key_name_2",
}

加载它

with open("<filepath>") as json_file:
format_dict = json.load(json_file)

创建此函数来使用映射格式化字典

def format_output(dict_to_format,format_dict):
for row in dict_to_format:
if row in format_dict.keys() and row != format_dict[row]:
dict_to_format[format_dict[row]] = dict_to_format.pop(row)
return dict_to_format
< p > # EYZ0
# EYZ0
orig_dict['AAAAA'] = orig_dict.pop('A')

orig_dict = {'A': 1, 'B' : 5,  'C' : 10, 'D' : 15}
# printing initial
print ("original: ", orig_dict)


# changing keys of dictionary
orig_dict['AAAAA'] = orig_dict.pop('A')
  

# printing final result
print ("Changed: ", str(orig_dict))


我在下面写了这个函数,您可以将当前键名的名称更改为新名称。

def change_dictionary_key_name(dict_object, old_name, new_name):
'''
[PARAMETERS]:
dict_object (dict): The object of the dictionary to perform the change
old_name (string): The original name of the key to be changed
new_name (string): The new name of the key
[RETURNS]:
final_obj: The dictionary with the updated key names
Take the dictionary and convert its keys to a list.
Update the list with the new value and then convert the list of the new keys to
a new dictionary
'''
keys_list = list(dict_object.keys())
for i in range(len(keys_list)):
if (keys_list[i] == old_name):
keys_list[i] = new_name


final_obj = dict(zip(keys_list, list(dict_object.values())))
return final_obj

假设一个JSON,你可以调用它,并通过以下行重命名它:

data = json.load(json_file)
for item in data:
item = change_dictionary_key_name(item, old_key_name, new_key_name)

从列表键到字典键的转换在这里:
https://www.geeksforgeeks.org/python-ways-to-change-keys-in-dictionary/

使用熊猫你可以得到这样的东西,

from pandas import DataFrame
df = DataFrame([{"fruit":"apple", "colour":"red"}])
df.rename(columns = {'fruit':'fruit_name'}, inplace = True)
df.to_dict('records')[0]
>>> {'fruit_name': 'apple', 'colour': 'red'}

用下划线替换字典键中的空格,我用这个简单的路线…

for k in dictionary.copy():
if ' ' in k:
dictionary[ k.replace(' ', '_') ] = dictionary.pop(k, 'e r r')

# eyz1 # eyz0 # eyz2

.copy()避免…字典在迭代过程中改变了大小。

.keys()不需要,k是每个键,k在我的头脑中代表键。

(我使用v3.7)

关于dictionary pop()的信息

上面循环的一行代码是什么?

你可以使用iff/else字典理解。此方法允许您在一行中替换任意数量的键,并且不需要更改所有键。

key_map_dict = {'a':'apple','c':'cat'}
d = {'a':1,'b':2,'c':3}
d = {(key_map_dict[k] if k in key_map_dict else k):v  for (k,v) in d.items() }

返回# EYZ0

我只是要帮我妻子做一些python类的事情,所以我写了这段代码来告诉她如何做。正如标题所示,它只替换键名。这是非常罕见的,你必须替换一个键名,并保持字典的顺序完整,但我还是想分享,因为这篇文章是当你搜索它时谷歌返回的,即使它是一个非常老的线程。

代码:

dictionary = {
"cat": "meow",
"dog": "woof",
"cow": "ding ding ding",
"goat": "beh"
}




def countKeys(dictionary):
num = 0
for key, value in dictionary.items():
num += 1
return num




def keyPosition(dictionary, search):
num = 0
for key, value in dictionary.items():
if key == search:
return num
num += 1




def replaceKey(dictionary, position, newKey):
num = 0
updatedDictionary = {}
for key, value in dictionary.items():
if num == position:
updatedDictionary.update({newKey: value})
else:
updatedDictionary.update({key: value})
num += 1
return updatedDictionary




for x in dictionary:
print("A", x, "goes", dictionary[x])
numKeys = countKeys(dictionary)


print("There are", numKeys, "animals in this list.\n")
print("Woops, that's not what a cow says...")


keyPos = keyPosition(dictionary, "cow")
print("Cow is in the", keyPos, "position, lets put a fox there instead...\n")
dictionary = replaceKey(dictionary, keyPos, "fox")


for x in dictionary:
print("A", x, "goes", dictionary[x])

输出:

A cat goes meow
A dog goes woof
A cow goes ding ding ding
A goat goes beh
There are 4 animals in this list.


Woops, that's not what a cow says...
Cow is in the 2 position, lets put a fox there instead...


A cat goes meow
A dog goes woof
A fox goes ding ding ding
A goat goes beh