Search code examples
pythonlistdictionarygrouping

get list of lists from dict of lists by grouping elements at same index in every key-value pair


I have a dictionary

  a = {'a':[1,2,3],'b':[4,5,6]}

Now, I wish to convert it into a list of lists such that

  [[1,4],[2,5],[3,6]]

i.e. the 1st element of every key-value pair grouped together, every 2nd element grouped together & likewise. Also, number of keys isn't restricted to 2 & can be 'n'


Solution

  • If you're fine with the results being tuples rather than lists an easy way is:

    list(zip(*a.values()))
    

    else sprinkling in some list comprehension can cast to the correct type:

    [list(value_pair) for value_pair in zip(*a.values())]