2

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)
vaultah
  • 44,105
  • 12
  • 114
  • 143
harumomo503
  • 371
  • 1
  • 7
  • 16
  • 4
    `zip(*your_dict.values())` – mshsayem Aug 26 '15 at 09:17
  • That was my attempt but it didn't give me what I want.. It was like [(1,2,3),(4,5,6)] – harumomo503 Aug 26 '15 at 09:18
  • Oh.. wait star in the front.. Thank you! I didn't know about this star in the front. It works! Thanks – harumomo503 Aug 26 '15 at 09:18
  • the 'star in front' unpacks the items from the sequence given by `your_dict.values()` and turns them into separate arguments which are passed to the `zip` function. Please read [this SO QA](http://stackoverflow.com/questions/12786102/unpacking-function-argument) – Pynchia Aug 26 '15 at 09:33

1 Answers1

10

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)]
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • There's no way to sort this automatically by the dict keys? For a large dictionary, this is not suitable. – nad7wf Mar 16 '21 at 18:03