Skip to content

Instantly share code, notes, and snippets.

@Ronserruya
Created December 3, 2019 14:04
Show Gist options
  • Select an option

  • Save Ronserruya/91ed3713e25fcd36aabb243ce8f31525 to your computer and use it in GitHub Desktop.

Select an option

Save Ronserruya/91ed3713e25fcd36aabb243ce8f31525 to your computer and use it in GitHub Desktop.
Python merge dicts without overwriting inner values
def update_key(key, value, d: dict):
if key not in d:
d[key] = value
else:
if isinstance(value, dict):
for k, v in value.items():
update_key(k, v, d[key])
else:
raise RuntimeError('Trying to overwrite existing value')
```
my_dict = {}
update_key('name', 'ron', my_dict)
print(my_dict)
{'name': 'ron'}
update_key('location', {'country': 'Israel'}, my_dict)
print(my_dict)
{'name': 'ron', 'location': {'country': 'Israel'}}
update_key('location', {'city': 'aaa', 'street': 'bbb'}, my_dict)
print(my_dict)
{'name': 'ron', 'location': {'country': 'Israel', 'city': 'aaa', 'street': 'bbb'}}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment