Created
December 3, 2019 14:04
-
-
Save Ronserruya/91ed3713e25fcd36aabb243ce8f31525 to your computer and use it in GitHub Desktop.
Python merge dicts without overwriting inner values
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
| 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