Zipping a dictionary whose values are lists
Alexander Blinne
news at blinne.net
Fri Apr 13 11:58:33 EDT 2012
Am 12.04.2012 18:38, schrieb Kiuhnm:
> Almost. Since d.values() = [[1,2], [1,2,3], [1,2,3,4]], you need to use
> list(zip(*d.values()))
> which is equivalent to
> list(zip([1,2], [1,2,3], [1,2,3,4]))
>
> Kiuhnm
While this accidently works in this case, let me remind you that
d.values() does not return the elements of the d in any specific order.
(It is a non-random but implementation-specific order, see
<http://docs.python.org/library/stdtypes.html#dict.items>.) Thus if you
need the correct order (as suggested by the dict keys) an explicit
sorting step is required, for example
zip(*[x[1] for x in sorted(d.items(), key=lambda y: y[0])])
Greetings
More information about the Python-list
mailing list