Zipping a dictionary whose values are lists
Kiuhnm
kiuhnm03.4t.yahoo.it
Thu Apr 12 12:38:52 EDT 2012
On 4/12/2012 18:28, tkpmep at gmail.com wrote:
> 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],)]
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
More information about the Python-list
mailing list