Vincent
Vincent

Reputation: 17

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?

Upvotes: 0

Views: 672

Answers (3)

Ajax1234
Ajax1234

Reputation: 71451

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

Upvotes: 2

Nouman
Nouman

Reputation: 7303

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

Upvotes: 0

jpp
jpp

Reputation: 164613

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

Upvotes: 1

Related Questions