Reputation: 407
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'}]
Upvotes: 0
Views: 32
Reputation: 5939
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']
Upvotes: 0
Reputation: 24233
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.
Upvotes: 1