Home > OS >  How to merge list of dictionaries by key?
How to merge list of dictionaries by key?

Time:09-28

How can I turn the following list:

[{'xx1': {'test1': 8}}, {'xx1': {'test3': 2}}, {'yy2': {'test1': 5}}, {'yy2': {'test5': 6}}]

into

[{'xx1' : {'test1': 8, 'test3':2}, 'yy2' : {'test1': 5, 'test5': 6}}]

What is the syntactically cleanest way to accomplish this? Or, how can it be done by using reduce()?

Thanks for any help!!

CodePudding user response:

something like the below

from collections import defaultdict

data = defaultdict(dict)
lst = [{'xx1': {'test1': 8}}, {'xx1': {'test3': 2}}, {'yy2': {'test1': 5}}, {'yy2': {'test5': 6}}]

for entry in lst:
    for k, v in entry.items():
        kk, vv = next(iter(v.items()))
        data[k][kk] = vv
print(data)

output

defaultdict(<class 'dict'>, {'xx1': {'test1': 8, 'test3': 2}, 'yy2': {'test1': 5, 'test5': 6}})

CodePudding user response:

You can try this:

def fnd_val(lst_dct, key):
    lst = ([ld[key] for ld in lst_dct if key in ld])
    return dict(j for i in lst for j in i.items())
            
lst_dct = [{'xx1': {'test1': 8}}, {'xx1': {'test3': 2}}, {'yy2': {'test1': 5}}, {'yy2': {'test5': 6}}]      
out = {}
for ld in lst_dct:
    for k,v in ld.items():
        out[k] = fnd_val(lst_dct, k)

print(out)

Output:

{'xx1': {'test1': 8, 'test3': 2}, 'yy2': {'test1': 5, 'test5': 6}}
  • Related