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


当前回答

转换字典中的所有键

假设这是你的字典:

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

其他回答


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

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

或者只是dictionary。pop(k)注意'e r r',它可以是任何字符串,如果键不在字典中,就会成为新的值,从而能够替换它,这在这里不可能发生。参数是可选的,在其他类似的代码中,KeyError可能会被击中,添加的arg会避免它,但可以创建一个新的键'e rr '或任何你设置的值。

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

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

(我使用v3.7)

关于字典pop()的信息

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

只需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

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

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

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

没有理由不能添加紫色->2或删除红色->1并添加橙色->1

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

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

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

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/