将不同字典列表中的 Python 密钥名称更改为另一个密钥名称



在不相同的字典列表中,随机使用两个不同的键名称来保存相同类型的值。例如"动物"和"野兽",但都应该只是"动物":

list = [{'beast': 'dog', 'age': 3, 'weather': 'cold'},
{'animal': 'cat', 'age': 2, 'food': 'catnip'},
{'animal': 'bird', 'age': 15, 'cage': 'no'}]
我需要将键[">

野兽"]替换为键["动物"]。

我已经尝试了以下方法,但只有在所有相关键都是"野兽"时才有效,然后可以重命名为"动物":

for pet in list:
pet['animal'] = pet['beast'] 
del pet['beast']

这同样适用于另一种方式:

for pet in list:
pet['animal'] = pet.pop('beast')

我希望输出变成:

[{'age': 3, 'weather': 'cold', '**animal**': 'dog'},
{'age': 2, 'food': 'catnip', '**animal**': 'cat'},
{'age': 15, 'cage': 'no', '**animal**': 'bird'}]

只需在替换密钥之前检查密钥是否存在:

data =  [{'beast': 'dog', 'age': 3, 'weather': 'cold'},
{'animal': 'cat', 'age': 2, 'food': 'catnip'},
{'animal': 'bird', 'age': 15, 'cage': 'no'}]
for d in data:
if 'beast' in d:
d['animal'] = d.pop('beast')

print(data)
# [{'age': 3, 'weather': 'cold', 'animal': 'dog'}, 
#  {'animal': 'cat', 'age': 2, 'food': 'catnip'}, 
#  {'animal': 'bird', 'age': 15, 'cage': 'no'}]

作为旁注,我将列表的名称从list更改为data,因为list是内置的 Python,并且命名list隐藏原始函数的东西。

包括上面提到的if句子在第一种情况下也很有效:

for pet in list:
if 'beast' in pet:
pet['animal'] = pet['beast'] 
del pet['beast']

最新更新