简体   繁体   中英

How to add dictionary values from a list in a for loop

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!

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.

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