Combining two Python dictionaries in a dictionary with the same key

I am going to combine the two dictionaries shown below, but I have not been successful.

I read a lot of blog posts, but I did not find the answer.

dict1={"KPNS": {"metadocdep": {"eta": {"sal": "2"}}, "metadocdisp": {"meta": {"head": "1"}}}, "EGLS": {"apns": {"eta": {"sal": "2"}}, "gcm": {"meta": {"head": "1"}}}}

dict2={"KPNS": {"metadocdep": {"eta": {"sal": "7"}}, "metadocdisp": {"meta": {"head": "5"}}}, "EGLS": {"apns": {"eta": {"sal": "7"}}, "gcm": {"meta": {"head": "9"}}}}
finaldict = {key:(dict1[key], dict2[key]) for key in dict1}

print finaldict

My end result should look like this:

{"KPNS": {"metadocdep": {"eta": {"sal": [2,7]}},
          "metadocdisp": {"meta": {"head": [1,5]}}},
 "EGLS": {"apns": {"eta": {"sal": [2,7]}},
          "gcm": {"meta": {"head": [1,9]}}}}

How can i do this?

+4
source share
1 answer

With defaultdict

If you know what the expected depth is, you can use the nested defaultdicts to determine final_dict:

from collections import defaultdict

final_dict = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))

final_dict['a']['b']['c'].append(1)
print(final_dict)
# defaultdict(<function <lambda> at 0x7f2ae7f41e18>, {'a': defaultdict(<function <lambda>.<locals>.<lambda> at 0x7f2ae636b730>, {'b': defaultdict(<class 'list'>, {'c': [1]})})})

There is a lot of added output due defaultdict, but you can consider it final_dictas a simple dict.

Using dicts

With standard dicts you will need to use setdefault. The code does not get very readable, but:

dict1 = {"KPNS": {"metadocdep": {"eta": {"sal": "2"}}, "metadocdisp": {"meta": {
    "head": "1"}}}, "EGLS": {"apns": {"eta": {"sal": "2"}}, "gcm": {"meta": {"head": "1"}}}}

dict2 = {"KPNS": {"metadocdep": {"eta": {"sal": "7"}}, "metadocdisp": {"meta": {
    "head": "5"}}}, "EGLS": {"apns": {"eta": {"sal": "7"}}, "gcm": {"meta": {"head": "9"}}}}

final_dict = {}
for d in [dict1, dict2]:
    for level1 in d:
        for level2 in d[level1]:
            for level3 in d[level1][level2]:
                for level4 in d[level1][level2][level3]:
                    final_dict.setdefault(level1, {}).setdefault(level2, {}).setdefault(
                        level3, {}).setdefault(level4, []).append(d[level1][level2][level3][level4])

print(final_dict)
# {'KPNS': {'metadocdep': {'eta': {'sal': ['2', '7']}}, 'metadocdisp': {'meta': {'head': ['1', '5']}}}, 'EGLS': {'apns': {'eta': {'sal': ['2', '7']}}, 'gcm': {'meta': {'head': ['1', '9']}}}}

dict.items():

for d in [dict1, dict2]:
    for level1, d2s in d.items():
        for level2, d3s in d2s.items():
            for level3, d4s in d3s.items():
                for level4, v in d4s.items():
                    final_dict.setdefault(level1, {}).setdefault(level2, {}).setdefault(
                        level3, {}).setdefault(level4, []).append(v)
+3

Source: https://habr.com/ru/post/1687453/


All Articles