简体   繁体   中英

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. 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'].

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.

Including the above mentioned if sentence works well in a first case as well:

for pet in list:
    if 'beast' in pet:
        pet['animal'] = pet['beast'] 
        del pet['beast']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM