Reputation: 57
I have a list of dictionaries called test:
test = [
{
'age': 15,
'country': 'Canada'
},
{
'age': 21,
'country': 'Denmark'
},
{
'age': 35,
'country': 'USA'
},
{
'age': 55,
'country': 'Canada'
}
]
To each dictionary I would like to add a new key called 'degrees' and a value from the following list:
listy = [0,1,1,2]
My desired outcome would be the following:
[{'age': 15, 'country': 'Canada', 'degrees': 0},
{'age': 21, 'country': 'Denmark', 'degrees': 1},
{'age': 35, 'country': 'USA', 'degrees': 1},
{'age': 55, 'country': 'Canada', 'degrees': 2}]
I have tried:
listy = [0,1,1,2]
for num,n in enumerate(test):
n['degrees'] = listy[num]
but that throws an error... I think there is a simple solution but I am stumped. I appreciate any help - Thanks in advance!
Upvotes: 0
Views: 84
Reputation: 5183
You can use zip
to simultaneously iterate over the dictionaries and the new values, which is a little faster than indexing on each iteration
for each_dict, value in zip(test, listy):
each_dict['degrees'] = value
Since lists and dictionaries are both mutable, then modifying each_dict
will update the list.
Upvotes: 6