Home > Software engineering >  Convert an array of dicts to array of arrays based on dicts values
Convert an array of dicts to array of arrays based on dicts values

Time:05-28

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)

CodePudding user response:

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())
  • Related