简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM