Home > Enterprise >  Grouping elements at an index together in a list inside a dictionary
Grouping elements at an index together in a list inside a dictionary

Time:06-02

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,

CodePudding user response:

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']]

CodePudding user response:

Try:

from itertools import zip_longest

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

dummy = object()
out = [
    [v for v in t if v is not dummy]
    for t in zip_longest(*bbox.values(), fillvalue=dummy)
]
print(out)

Prints:

[["a", "d", "f", "h", "i"], 
 ["b", "e", "g", "j"], 
 ["c", "k"], 
 ["l"], 
 ["m"]]
  • Related