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


当前回答

只需2步即可轻松完成:

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

或者一步:

dictionary[new_key] = dictionary.pop(old_key)

如果字典[old_key]未定义,将引发KeyError。注意,这将删除字典[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

其他回答

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

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

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/

以防一次换了所有的钥匙。 我在这里阻塞钥匙。

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

对于熊猫,你可以有这样的东西,

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'}

如果你想更改所有的键:

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}

如果你想改变单键: 你可以选择上面的任何一个建议。