Zipping a dictionary whose values are lists

T

tkpmep

I using Python 3.2 and have a dictionary
d = {0:[1,2], 1:[1,2,3], 2:[1,2,3,4]}

whose values are lists I would like to zip into a list of tuples. If I explicitly write:
list(zip([1,2], [1,2,3], [1,2,3,4])
[(1, 1, 1), (2, 2, 2)]

I get exactly what I want. On the other hand, I have tried
[(0,), (1,), (2,)]
[([1, 2],), ([1, 2, 3],), ([1, 2, 3, 4],)]

[([1, 2],), ([1, 2, 3],), ([1, 2, 3, 4],)]
Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
list(zip(*d))
TypeError: zip argument #1 must support iteration

and nothing quite works. What am I doing wrong?

Sincerely

Thomas Philips
 
A

Alexander Blinne

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top