categories = {'player_name': None, 'player_id': None, 'season': None}
L = ['Player 1', 'player_1', '2020']
如何遍历列表并将其值分配给相应的键?所以它会变成这样:
{'player_name': 'Player 1', 'player_id': 'player_1, 'season': '2020'}
谢谢
答案 0 :(得分:3)
如果python> = 3.6,则使用zip()
+ dict()
,如果<3.6,则看起来dict是无序的,所以我不知道。
test.py :
categories = {'player_name': None, 'player_id': None, 'season': None}
L = ['Player 1', 'player_1', '2020']
print(dict(zip(categories, L)))
结果:
$ python3 test.py
{'player_name': 'Player 1', 'player_id': 'player_1', 'season': '2020'}
答案 1 :(得分:2)
categories = { '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
这应该可以解决您的问题
答案 2 :(得分:2)
如果列表中的项与字典具有键的顺序相同,即,如果player_name是列表中的第一个元素,则字典中的“ player_name”应排在首位
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
答案 3 :(得分:2)
您可以尝试这样的事情
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)