在不同字典的列表中,随机使用两个不同的键名称来保存相同类型的值。例如“动物”和“野兽”,但都应为“动物”:
list = [{'beast': 'dog', 'age': 3, 'weather': 'cold'},
{'animal': 'cat', 'age': 2, 'food': 'catnip'},
{'animal': 'bird', 'age': 15, 'cage': 'no'}]
我需要将key ['beast']替换为key ['animal']。
我已经尝试了以下方法,但是仅当所有相关键都是“野兽”,然后可以将其重命名为“动物”时才有效:
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
是Python内置的,因此我将列表的名称从data
更改为list
,并命名list
遮盖了原始函数。
包括上述if
句子在第一种情况下也很好用:
for pet in list:
if 'beast' in pet:
pet['animal'] = pet['beast']
del pet['beast']