Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zipping a python dict of lists

Tags:

python

I have a python dictionary of type defaultdict(list) This dictionary is something like this:

a = {1:[1,2,3,4],2:[5,6,7,8]....n:[some 4 elements]}

So basically it has n keys which has a list as values and all the list are of same lenght. Now, i want to build a list which has something like this.

[[1,5,...first element of all the list], [2,6.. second element of all the list]... and so on]

Soo basically how do i get the kth value from all the keys.. Is there a pythonic way to do this.. ?? THanks

like image 776
frazman Avatar asked Dec 02 '25 05:12

frazman


2 Answers

>>> a = {1:[1,2,3,4],2:[5,6,7,8], 3:[9, 10, 11, 12]}
>>> 
>>> zip(*(a[k] for k in sorted(a)))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

(Okay, this produces tuples, not lists, but hopefully that's not a problem.)

Update: I like the above more than this, but the following is a few keystrokes shorter:

>>> zip(*map(a.get, sorted(a)))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
like image 79
DSM Avatar answered Dec 03 '25 21:12

DSM


How about this solution: zip(*a.values())

For e.g.

>>> a = {1:[1,2,3,4],2:[5,6,7,8], 3:[9, 10, 11, 12]}
>>> zip(*a.values())
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

Update: to preserve order use DSM's answer.

like image 35
Manoj Govindan Avatar answered Dec 03 '25 20:12

Manoj Govindan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!