Search code examples
pythondictionarydefaultdict

How can i combine a list of dicts to a list of dicts combining like keys


I want to take this input:

mycounter = [{6: ['Credit card']}, {2: ['Debit card']}, {2: ['Check']}]                                                                                                                                                        
#[{6: ['Credit card']}, {2: ['Debit card']}, {2: ['Check']}]

And achieve this Desired Output:

[{6: ['Credit card']}, {2: ['Debit card', 'Check']}]

My attempt was the following, but it's not matching desired output. Any help here is appreciated. Thx.

temp = list(zip([*map(lambda d: next(iter(d.keys())), mycounter)], [*map(lambda d: next(iter(d.values())), mycounter)]))  

c = collections.defaultdict(list)
for a,b in temp:
   c[a].extend(b)

final = [dict(c)]
# Close, but not quite the desired output since it's should be two dict objects, not one
# [{6: ['Credit card'], 2: ['Debit card', 'Check']}]

My searches on stackoverflow found solutions that combine with giving None values, but nothing like what i'm asking for. My question has a different input than another similar question earlier.


Solution

  • One option would be to make a single dictionary then break it into single key-value pairs after:

    mycounter = [{6: ['Credit card']}, {2: ['Debit card']}, {2: ['Check']}]                                                                                                                                                        
    
    res = {}
    for d in mycounter:
        for k, v in d.items():
            res.setdefault(k, []).extend(v)
    [{k:v} for k, v in res.items()]
    # [{6: ['Credit card']}, {2: ['Debit card', 'Check']}]