'Combine Python dictionaries that have the same Key name

I have two separate Python List that have common key names in their respective dictionary. The second list called recordList has multiple dictionaries with the same key name that I want to append the first list clientList. Here are examples lists:

clientList = [{'client1': ['c1','f1']}, {'client2': ['c2','f2']}]
recordList = [{'client1': {'rec_1':['t1','s1']}}, {'client1': {'rec_2':['t2','s2']}}]

So the end result would be something like this so the records are now in a new list of multiple dictionaries within the clientList.

 clientList = [{'client1': [['c1','f1'], [{'rec_1':['t1','s1']},{'rec_2':['t2','s2']}]]}, {'client2': [['c2','f2']]}]

Seems simple enough but I'm struggling to find a way to iterate both of these dictionaries using variables to find where they match.



Solution 1:[1]

Assuming you want a list of values that correspond to each key in the two lists, try this as a start:

from pprint import pprint

clientList = [{'client1': ['c1','f1']}, {'client2': ['c2','f2']}]
recordList = [{'client1': {'rec_1':['t1','s1']}}, {'client1': {'rec_2':['t2','s2']}}]
clientList.extend(recordList)

outputList = {}

for rec in clientList:
    k = rec.keys()[0]
    v = rec.values()[0]
    if k in outputList:
        outputList[k].append(v)
    else:
        outputList[k] = [v,]

pprint(outputList)

It will produce this:

{'client1': [['c1', 'f1'], {'rec_1': ['t1', 's1']}, {'rec_2': ['t2', 's2']}],
 'client2': [['c2', 'f2']]}

Solution 2:[2]

This could work but I am not sure I understand the rules of your data structure.

# join all the dicts for better lookup and update
clientDict = {}
for d in clientList:
    for k, v in d.items():
        clientDict[k] = clientDict.get(k, []) + v

recordDict = {}
for d in recordList:
    for k, v in d.items():
        recordDict[k] = recordDict.get(k, []) + [v]

for k, v in recordDict.items():
    clientDict[k] = [clientDict[k]] + v

# I don't know why you need a list of one-key dicts but here it is
clientList = [dict([(k, v)]) for k, v in clientDict.items()]

With the sample data you provided this gives the result you wanted, hope it helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 daedalus
Solution 2 Facundo Casco