[英]Change Python Key name in a list of non-identical dictionaries to another Key name
In a list of non-identical dictionaries, two different Key names are randomly used to hold the same kind of value.在不相同的字典列表中,随机使用两个不同的 Key 名称来保存相同类型的值。 For example "animal" and "beast" but all should just be "animal":例如“动物”和“野兽”,但都应该是“动物”:
list = [{'beast': 'dog', 'age': 3, 'weather': 'cold'},
{'animal': 'cat', 'age': 2, 'food': 'catnip'},
{'animal': 'bird', 'age': 15, 'cage': 'no'}]
I need to replace key['beast'] with key['animal'].我需要用 key['animal'] 替换 key['beast']。
I have tried the following but only works if all the relevant Keys are "beast" which then can be renamed to "animal":我尝试了以下操作,但仅当所有相关键都是“野兽”时才有效,然后可以将其重命名为“动物”:
for pet in list:
pet['animal'] = pet['beast']
del pet['beast']
The same applies for another way:这同样适用于另一种方式:
for pet in list:
pet['animal'] = pet.pop('beast')
I'd like the output to become:我希望输出变成:
[{'age': 3, 'weather': 'cold', '**animal**': 'dog'},
{'age': 2, 'food': 'catnip', '**animal**': 'cat'},
{'age': 15, 'cage': 'no', '**animal**': 'bird'}]
Just check if the key exists before replacing it:在替换之前检查密钥是否存在:
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'}]
As a side note, I changed the name of your list from list
to data
, as list
is a Python builtin, and naming something list
shadows the original function.附带说明一下,我将列表的名称从list
更改为data
,因为list
是 Python 内置函数,并且将某些内容命名为list
影响原始函数。
Including the above mentioned if
sentence works well in a first case as well:包括上面提到的if
句子在第一种情况下也能正常工作:
for pet in list:
if 'beast' in pet:
pet['animal'] = pet['beast']
del pet['beast']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.