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

Convert one dictionary to list of dictionaries

I need to convert one dictionary, whose values are in a list to a list of dictionaries.

For example, the following dictionary:

only_dict = {'First': [1, 2], 'Second': [3, 4]}

Should have the following output, where values are no longer in a list.

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

out_lst = [{'First': 1, 'Second': 3}, {'First': 2, 'Second': 4}]

>Solution :

A simple version for any length of the lists. First, get the maximum list length:

count = max(*[len(x) for x in only_dict])

Construct each of the dictionaries one by one:

out_lst = [{k: v[i] for k, v in only_dict.items() if len(v) >= i} for i in range(count)]
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