Zipping a dictionary whose values are lists

Shambhu Rajak Shambhu.Rajak at kpitcummins.com
Fri Apr 13 03:02:35 EDT 2012


The below code should work:
zip(*d.values())

when you do *d.values() its going to return tuple of elements, which then further be can be zipped to 
achieve  your desired result.

Regards,
Shambhu Rajak
Python Lover

-----Original Message-----
From: tkpmep at gmail.com [mailto:tkpmep at gmail.com] 
Sent: 12/04/2012 9:58 PM
To: python-list at python.org
Subject: Zipping a dictionary whose values are lists

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

>>>list(zip(d))
[(0,), (1,), (2,)]

>>> list(zip(d.values()))
[([1, 2],), ([1, 2, 3],), ([1, 2, 3, 4],)]

>>> list(zip(d[i] for i in d))
[([1, 2],), ([1, 2, 3],), ([1, 2, 3, 4],)]

>>> list(zip(*d))
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





More information about the Python-list mailing list