zip two values from the dictionary in Python

后端 未结 1 1230
耶瑟儿~
耶瑟儿~ 2021-01-21 11:37

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
相关标签:
1条回答
  • 2021-01-21 12:34

    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)]
    
    0 讨论(0)
提交回复
热议问题