Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert this list into a dictionary

I have a list currently that looks like this

list =  [['hate', '10'], ['would', '5'], ['hello', '10'], ['pigeon', '1'], ['adore', '10']]

I want to convert it to a dictionary like this

dict = {'hate': '10', 'would': '5', 'hello': '10', 'pigeon': '1', 'adore': '10'}

So basically the list [i][0] will be the key and the list [i][1] will be values. Any help would be really appreciated :)

like image 223
John Gringus Avatar asked Dec 24 '22 12:12

John Gringus


1 Answers

Use the dict constructor:

In [1]: lst =  [['hate', '10'], ['would', '5'], ['hello', '10'], ['pigeon', '1'], ['adore', '10']]

In [2]: dict(lst)
Out[2]: {'adore': '10', 'hate': '10', 'hello': '10', 'pigeon': '1', 'would': '5'}

Note that from your edit it seems you need the values to be integers rather than strings (e.g. '10'), in which case you can cast the second item of each inner list into an int before passing them to dict:

In [3]: dict([(e[0], int(e[1])) for e in lst])
Out[3]: {'adore': 10, 'hate': 10, 'hello': 10, 'pigeon': 1, 'would': 5}
like image 56
xnx Avatar answered Jan 09 '23 15:01

xnx