Created
February 14, 2023 23:44
-
-
Save shubhamkumar13/5afbb31a8cde18a59f2abb9ceff98766 to your computer and use it in GitHub Desktop.
merge 2 dictionaries in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# dict1 : { | |
# "a" : 1, | |
# "b" : "3", | |
# "c" : (4,), | |
# "d" : [3], | |
# "e" : {"f" : 7}, | |
# } | |
# dict2 : { | |
# "a" : 2, | |
# "b" : "4", | |
# "c" : (3,), | |
# "d" : [7], | |
# "e" : {"g" : 8}, | |
# } | |
def type_of(val1: any, val2: any): | |
types = [int, str, tuple, list, dict] | |
fst_type_list = map(lambda type: (isinstance(val1, type), type), types) | |
snd_type_list = map(lambda type: (isinstance(val2, type), type), types) | |
return [fst[1] for (fst, snd) in | |
zip(fst_type_list, snd_type_list) if (fst[0] and snd[0])][0] | |
def merge(dict1: dict, dict2: dict) -> dict: | |
switch = { | |
int: lambda a, b: a + b, | |
str: lambda a, b: a + b, | |
tuple: lambda a, b: a + b, | |
list: lambda a, b: a + b, | |
dict: lambda a, b: merge(a, b)} | |
key_set1 = set(dict1.keys()) | |
key_set2 = set(dict2.keys()) | |
common_keys = key_set1.intersection(key_set2) | |
disjoint_key1 = key_set1.difference(key_set2) | |
disjoint_key2 = key_set2.difference(key_set1) | |
updated_dict = dict( | |
(k, switch[type_of(dict1[k], dict2[k])](dict1[k], dict2[k])) | |
for k in common_keys | |
) | |
disjoint_dict1 = dict((k, dict1[k]) for k in disjoint_key1) | |
disjoint_dict2 = dict((k, dict2[k]) for k in disjoint_key2) | |
disjoint_dict = dict(**disjoint_dict1, **disjoint_dict2) | |
updated_dict = dict(**updated_dict, **disjoint_dict) | |
return updated_dict | |
def main(): | |
dict1 = { | |
"a": 1, | |
"b": "3", | |
"c": (4,), | |
"d": [3], | |
"e": {"f": 7}, | |
} | |
dict2 = { | |
"a": 2, | |
"b": "4", | |
"c": (3,), | |
"d": [7], | |
"e": {"f": 6, "g": 8}, | |
} | |
print(merge(dict1.copy(), dict2.copy())) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment