Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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())]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading