Aysennoussi
Aysennoussi

Reputation: 3860

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)

Upvotes: 1

Views: 68

Answers (1)

mozway
mozway

Reputation: 260825

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

Upvotes: 2

Related Questions