d = {'a':[1,2,3], 'b':[4,5]}
and I need
[1,2,3,4,5]
using list comprehension. How do I do it?
d = {'a':[1,2,3], 'b':[4,5]}
and I need
[1,2,3,4,5]
using list comprehension. How do I do it?
Use a nested list comprehension:
>>> [val for lst in d.values() for val in lst]
[1, 2, 3, 4, 5]
But you may need to sort the dictionary first (because dicts are unordered) to guarantee the order:
>>> [val for key in sorted(d) for val in d[key]]
[1, 2, 3, 4, 5]
sum(d.values(),[]) works but not performant because it applies a = a + b for each temp list.
Use itertools.chain.from_iterable instead:
import itertools
print(list(itertools.chain.from_iterable(d.values())))
or sorted version:
print(sorted(itertools.chain.from_iterable(d.values())))
chain.from_iterable is probably better and faster than unpacking (*d.values()).