[英]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.