How to convert this list to 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'}

Thus, basically there list [i][0]will be a key, but list [i][1]will be a value. Any help would be really appreciated :)

+4
source share
3 answers

Use the constructor dict:

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 you will need values ​​that should be integers, not strings (for example, '10'), in which case you can discard the second element of each internal list in intbefore 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}
+9

:

import numpy as np

array = np.array(list)
for i in xrange(len(list)):
    dict[array[i][0]] = array[i][1]

:

>>> dict
{'pigeon': '1', 'hate': '10', 'hello': '10', 'would': '5', 'adore': '10'}
+1
list =  [['hate', '10'], ['would', '5'], ['hello', '10'], ['pigeon', '1'], ['adore', '10']]

new_dict = dict(list)

:

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

Source: https://habr.com/ru/post/1616712/


All Articles