I have the following data:
data = [(1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3)]
and I want to create a dictionary which contains key-list value, how can I do this with a dictionary comprehension?
i.e.:
{1: [2,3,4]
2: [1,2,3]
}
I have tried the following but the list gets overwritten on every iteration.
{x: [y] for x,y in data}
You can use this dict-comprehension:
d = {x: [v for u,v in data if u == x] for x,y in data}
Note, however, that this is pretty inefficient, as it will loop the entire list n+1
times!
Better use just a plain-old for
loop:
d = {}
for x,y in data:
d.setdefault(x, []).append(y)
Alternatively, you could also use itertools.groupy
(as discovered by yourself):
groups = itertools.groupby(sorted(data), key=lambda x: x[0])
d = {k: [g[1] for g in group] for k, group in groups}
In all cases, d
ends up being {1: [2, 3, 4], 2: [1, 2, 3]}
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