Eunjin Cho Eunjin Cho - 22 days ago 7
Python Question

zip two values from the dictionary in Python

I am trying to zip two values in a dictionary using Python numpy but it's not very successful. What I mean by zipping is something like this:


  1. I have a dictionary called dict, and inside looks like
    {'a0': [1, 2, 3], 'a1': [4, 5, 6]}
    .

  2. Then I want to zip this dictionary dict values to:
    [(1, 4), (2, 5), (3, 6)]
    (one element from each key)


Answer

You need to unpack dict.values() when passing onto zip() . Example -

>>> d = {'a0': [1, 2, 3], 'a1': [4, 5, 6]}
>>> zip(*d.values())
[(4, 1), (5, 2), (6, 3)]

Please note using this method, the order of elements in the zipped inner lists are not guaranteed, as dictionary itself does not have any sense of order.

If you want a specific order, you would need to be explicit in your zip() call. Example -

>>> zip(d['a0'], d['a1'])
[(1, 4), (2, 5), (3, 6)]