Skip to content Skip to sidebar Skip to footer

Combining A Nested List Without Affecting The Key And Value Direction In Python

I have a program that stores data in a list. The current and desired output is in the format: # Current Input [{'Devices': ['laptops', 'tablets'], 'ParentCategory': ['computers',

Solution 1:

You can do something like this:

def convert(a):
    d = {}
    for x in a:
        for key,val in x.items():
            if key not in d:
                d[key] = []
            d[key] += val
    return d

Code above is for Python 3.

If you're on Python 2.7, then I believe that you should replace items with iteritems.


Solution 2:

Solution using a dict comprehension: build the merged dictionary first by figuring out which keys it should have, then by concatenating all the lists for each key. The set of keys, and each resulting list, are built using itertools.chain.from_iterable.

from itertools import chain

def merge_dicts(*dicts):
    return {
        k: list(chain.from_iterable( d[k] for d in dicts if k in d ))
        for k in set(chain.from_iterable(dicts))
    }

Usage:

>>> merge_dicts({'a': [1, 2, 3], 'b': [4, 5]}, {'a': [6, 7], 'c': [8]})
{'a': [1, 2, 3, 6, 7], 'b': [4, 5], 'c': [8]}
>>> ds = [
    {'Devices': ['laptops', 'tablets'],
     'ParentCategory': ['computers', 'computers']},
    {'Devices': ['touch'],
     'ParentCategory': ['phones']}
]
>>> merge_dicts(*ds)
{'ParentCategory': ['computers', 'computers', 'phones'],
 'Devices': ['laptops', 'tablets', 'touch']}

Post a Comment for "Combining A Nested List Without Affecting The Key And Value Direction In Python"