Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping elements at an index together in a list inside a dictionary

I have a big python dictionary of the following type:

bbox = {'0': [a, b, c, l, m],
       '1': [d, e],
       '2': [f, g],
       '3': [h],
       '4': [],
       '5': [i, j, k]}

I want to group elements at the same index together from each list. While ignoring the empty location. The output is like this:

output= [[a, d, f, h, i], 
         [b, e, g, j],
         [c, k],
         [l],
         [m]
        ]

The dictionary is big of (300 elements) and the number of elements at in each value list is unknown. Is there a function I can use for this?

Thanks,

like image 716
Muhammad Anas Raza Avatar asked Nov 19 '25 13:11

Muhammad Anas Raza


1 Answers

Use a defaultdict and hop

bbox = {'0': ['a', 'b', 'c', 'l', 'm'], '1': ['d', 'e'], '2': ['f', 'g'],
        '3': ['h'], '4': [], '5': ['i', 'j', 'k']}

# from collections import defaultdict
result = defaultdict(list)
for values in bbox.values():
    for i, v in enumerate(values):
        result[i].append(v)

final = list(result.values())
print(final)
# [['a', 'd', 'f', 'h', 'i'], ['b', 'e', 'g', 'j'], ['c', 'k'], ['l'], ['m']]
like image 74
azro Avatar answered Nov 21 '25 01:11

azro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!