players=[['Jim','16','2'], ['John','5','1'], ['Jenny','1','0']]
lst=['score', 'win']
我有上面的清单。我希望创建如下输出:
{'Jim': {'score': 16, 'won': 2}, 'John': {'score': 5, 'won': 1}, 'Jenny': {'score': 1, 'won': 0}}
有可能吗?
答案 0 :(得分:2)
您可以对zip
使用解包:
players=[['Jim','16','2'], ['John','5','1'], ['Jenny','1','0']]
lst=['score', 'win']
results = {a:dict(zip(lst, [int(i) for i in b])) for a, *b in players}
输出:
{'Jim': {'score': 16, 'win': 2}, 'John': {'score': 5, 'win': 1}, 'Jenny': {'score': 1, 'win': 0}}
答案 1 :(得分:1)
这是一种还将值转换为整数的解决方案:
res = {name: dict(zip(lst, map(int, scores))) for name, *scores in players}
{'Jenny': {'score': 1, 'win': 0},
'Jim': {'score': 16, 'win': 2},
'John': {'score': 5, 'win': 1}}
答案 2 :(得分:0)
>>> players=[['Jim','16','2'], ['John','5','1'], ['Jenny','1','0']]
>>> lst=['score', 'win']
>>> a = {}
>>> for player in players:
a[player[0]] = {lst[0]:player[1],lst[1]:player[2]}
>>> a
{'Jim': {'score': '16', 'win': '2'}, 'John': {'score': '5', 'win': '1'}, 'Jenny': {'score': '1', 'win': '0'}}
>>>