简体   繁体   中英

How to assign list values to dictionary keys?

categories =  {'player_name': None, 'player_id': None, 'season': None} 

L = ['Player 1', 'player_1', '2020']

How can I iterate over list and assign its values to the corresponding keys? so it would become something like:

{'player_name': 'Player 1', 'player_id': 'player_1, 'season': '2020'}

thanks

If python >= 3.6, then use zip() + dict() , if < 3.6, looks dict is un-ordered, so I don't know.

test.py :

categories =  {'player_name': None, 'player_id': None, 'season': None}
L = ['Player 1', 'player_1', '2020']
print(dict(zip(categories, L)))

Results:

$ python3 test.py
{'player_name': 'Player 1', 'player_id': 'player_1', 'season': '2020'}
cat = { 'player_name' : None, 'player_id ': None, 'season' : None }
L = ['Player 1', 'player_1', 2020]

j = 0 
for i in cat.keys():
    cat[i]  =  L[j]
    j += 1

This should solve your problem

If the list has items in the same order as dictionary has keys ie if player_name is the first element in the list then 'player_name' in the dictionary should come at first place

categories = {'player_name': None, 'player_id': None, 'season': None}
L = ['Player 1', 'player_1', '2020']

for key, value in zip(categories.keys(), L):
    categories[key] = value

You could try something like this

categories = {'name':None, 'id':None, 'season':None}
L = ['Player 1', 'player_1', '2020']

it = iter(L)
for x in it:
    categories['name'] = x
    categories['id'] = next(it)
    categories['season'] = next(it)
    

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