将不相同的词典列表中的Python键名更改为另一个键名

问题描述 投票:0回答:2

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

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'}]
python list dictionary
2个回答
0
投票

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

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遮盖了原始函数。


0
投票

包括上述if句子在第一种情况下也很好用:

for pet in list:
    if 'beast' in pet:
        pet['animal'] = pet['beast'] 
        del pet['beast']
© www.soinside.com 2019 - 2024. All rights reserved.