![](/img/trans.png)
[英]Python convert 3 lists to list of dictionaries with list name as key name
[英]Change Python Key name in a list of non-identical dictionaries to another Key name
在不相同的字典列表中,随机使用两个不同的 Key 名称来保存相同类型的值。 例如“动物”和“野兽”,但都应该是“动物”:
list = [{'beast': 'dog', 'age': 3, 'weather': 'cold'},
{'animal': 'cat', 'age': 2, 'food': 'catnip'},
{'animal': 'bird', 'age': 15, 'cage': 'no'}]
我需要用 key['animal'] 替换 key['beast']。
我尝试了以下操作,但仅当所有相关键都是“野兽”时才有效,然后可以将其重命名为“动物”:
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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.