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 an array of dicts to array of arrays based on dicts values

I have this array:

[{'id_1': 5}, {'id_2': 10}, {'id_2': 4}]

And I want the output as:

[
 [5],
 [10,4]
]

I tried looping and creating specific arrays to track the used indexes but I feel that there should be a more performant way that’s O(n) instead of O(n2)

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 :

You can use a defaultdict for a O(n) solution:

l = [{'id_1': 5}, {'id_2': 10}, {'id_2': 4}]

from collections import defaultdict
dic = defaultdict(list)
for d in l:
    for k,v in d.items():
        dic[k].append(v)

out = list(dic.values())

Output: [[5], [10, 4]]

Variant with setdefault:

dic = {}
for d in l:
    for k,v in d.items():
        dic.setdefault(k, []).append(v)
out = list(dic.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