I have a list like that :
[['0', '10'], ['0', '11'], ['0', '12'], ['1', '10'], ['1', '11']]
How can i group the elements in the list, for example like above?
['0': ['10','11','12']],['1': ['10','11']]
iterate - put into dictionary.
d = {}
l = [['0', '10'], ['0', '11'], ['0', '12'], ['1', '10'], ['1', '11']]
for p in l:
if p[0] in d:
d[p[0]].append(p[1])
else:
d[p[0]] = [p[1]]
>>> d
{'1': ['10', '11'], '0': ['10', '11', '12']}
using defaultdict:
from collections import defaultdict
d = defaultdict(list)
l = [['0', '10'], ['0', '11'], ['0', '12'], ['1', '10'], ['1', '11']]
for p in l:
d[p[0]].append(p[1])
one-liner: using dict comprehension (a little wasteful, but no imports and requires 2.7+)
>>> dd = {key: [i[1] for i in l if i[0] == key] for (key, value) in l}
>>> dd
{'1': ['10', '11'], '0': ['10', '11', '12']}
You could use collections.defaultdict:
import collections
l = [['0', '10'], ['0', '11'], ['0', '12'], ['1', '10'], ['1', '11']]
d = collections.defaultdict(list)
for k, v in l:
d[k].append(v)
print(d)
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