Programming, electronics, lifestyle

25 Jan 2023

Python: Merge two dicts by key

The python function to merge 2 dicts by key:

#! /usr/bin/env python3

def merge_dicts_by_key(d1: dict, d2: dict) -> dict:
    d = {}
    for key in set(list(d1.keys()) + list(d2.keys())):
        d[key] = {}
        if d1.get(key):
            for subkey in set(list(d1[key].keys())):
                d[key][subkey] = d1[key][subkey]
        if d2.get(key):
            for subkey in set(list(d2[key].keys())):
                 d[key][subkey] = d2[key][subkey]
    return d