简体   繁体   English

如何从嵌套列表创建字典

[英]How to create dictionary from nested list

players=[['Jim','16','2'], ['John','5','1'], ['Jenny','1','0']]
lst=['score', 'win']

I have the above lists. 我有以上清单。 I wish to create a output as follows: 我希望创建如下输出:

{'Jim': {'score': 16, 'won': 2}, 'John': {'score': 5, 'won': 1}, 'Jenny': {'score': 1, 'won': 0}}

Is it possible? 可能吗?

You can use unpacking with zip : 您可以使用zipzip

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}

Output: 输出:

{'Jim': {'score': 16, 'win': 2}, 'John': {'score': 5, 'win': 1}, 'Jenny': {'score': 1, 'win': 0}}

Here's one solution which also converts values to integers: 这是一种还将值转换为整数的解决方案:

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}}
>>> 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'}}
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM