'Python3 How can I convert list to dict
I have a list like:lst=[['a',1],['b',2],['a',3],['b',1],['a',1]]
How can I convert this to dictionary like that:dct={'a':[1,3,1],'b':[2,1]}
Solution 1:[1]
The default dictionary can help you
from collections import defaultdict
ddict = defaultdict(list)
data = [['a',1],['b',2],['a',3],['b',1],['a',1]]
for key, value in data:
ddict[key].append(value)
Solution 2:[2]
Try this:
lst = [['a',1],['b',2],['a',3],['b',1],['a',1]]
dct = {}
for [k, v] in lst:
dct[k] = dct[k] + [v] if k in dct else [v]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Carlos Horn |
| Solution 2 | bbbbbbbbb |
