Zipping a dictionary whose values are lists

Kiuhnm kiuhnm03.4t.yahoo.it
Fri Apr 13 12:35:07 EDT 2012


On 4/13/2012 17:58, Alexander Blinne wrote:
> 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.

The OP said nothing about ordering.
The fact that the keys are ordered might be accidental :)

> (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])])

Or
   zip(*[d[k] for k in sorted(d.keys())])

Kiuhnm



More information about the Python-list mailing list