Reputation: 79
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
Upvotes: 0
Views: 4416
Reputation: 228
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
Upvotes: 2
Reputation: 31664
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'}
Upvotes: 4
Reputation: 72
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)
Upvotes: 2
Reputation: 21
If the list has items in the same order as dictionary has keys i-e 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
Upvotes: 2