Created
September 7, 2022 22:02
-
-
Save jnbdz/c3ed1a92b1f56d5e36aeac78be225d3f to your computer and use it in GitHub Desktop.
Mergin dict (https://stackoverflow.com/questions/73640524/merge-two-multi-dimention-dict-and-only-add-what-is-missing/73640771#73640771)
This file contains 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
#!/usr/bin/env python3 | |
import copy | |
A = {'v1': {'configuration': {'$schema': '...', 'network': {'$schema': '...'}}}} | |
E = {'v1': {'configuration': {'network': {'entries': {'$schema': '...'}}}}} | |
expected = {'v1': {'configuration': {'$schema': '...', 'network': {'$schema': '...', 'entries': {'$schema': '...'}}}}} | |
#def safe_update_dict(d_to: dict, d_from: dict): | |
# for k in d_from: | |
# if k in d_to: | |
# if isinstance(d_to[k], dict): | |
# d_to[k] = safe_update_dict(d_to[k], d_from[k]) | |
# else: | |
# d_to[k] = d_from[k] | |
# return d_to | |
# | |
#rtn = safe_update_dict(A, E) | |
#print(str(rtn)) | |
#print(str(expected) == str(rtn)) | |
#def safe_update_dict(d_to: dict, d_from: dict, inplace: bool=False): | |
# def fn(d_to: dict, d_from: dict): | |
# for k in d_from: | |
# print(k) | |
# if k in d_to: | |
# if isinstance(d_to[k], dict): | |
# d_to[k] = safe_update_dict(d_to[k], d_from[k]) | |
# else: | |
# d_to[k] = d_from[k] | |
# return d_to | |
# if inplace: | |
# return fn(d_from, d_to) | |
# return fn(fn({}, d_from), d_to) | |
# | |
#rtn = safe_update_dict(A, E) | |
#print(str(expected) == str(rtn)) # True | |
def safe_update_dict(d_to: dict, d_from: dict, inplace: bool=False): | |
def fn(d_to: dict, d_from: dict): | |
for k in d_from: | |
if k in d_to: | |
if isinstance(d_to[k], dict): | |
d_to[k] = fn(d_to[k], d_from[k]) | |
else: | |
d_to[k] = d_from[k] | |
return d_to | |
if inplace: | |
return fn(d_to, d_from) | |
return fn(copy.deepcopy(d_to), d_from) | |
rtn = safe_update_dict(A, E) | |
print(str(expected) == str(rtn)) # True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment