简体   繁体   中英

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 :

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

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