簡體   English   中英

將不同字典列表中的 Python Key 名稱更改為另一個 Key 名稱

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM