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 :)
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With