Created
September 13, 2018 17:00
-
-
Save charlieparkes/dbf76c77fe40659651722b7183fdca6a to your computer and use it in GitHub Desktop.
Python Dict Tools
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
def update_nested(d, keys, val): | |
"""Updates a nested dictionary value. | |
Args: | |
dictionary (dict): The dict we'll be updating | |
keys (list): A set of keys pointing to a subvalue of a dict e.g. ['a', 'b'] -> dict['a']['b'] | |
val: A new value to set at dictionary[key1][key2][..] | |
Returns: | |
dict: Updated dictionary | |
""" | |
current = d | |
for key in keys[:-1]: | |
current = current.setdefault(key, {}) | |
current[keys[-1]] = val | |
return d | |
def set_nested_path(d, path, val): | |
keys = path.split(‘.’) | |
return set_nested(d, keys, val) | |
def get_nested(d, keys): | |
"""Given a dictionary, fetch a key nested several levels deep.""" | |
head = d | |
for k in keys: | |
head = head.get(k, {}) | |
if not head: | |
return head | |
return head | |
def get_nested_path(d, path): | |
keys = path.split(‘.’) | |
return get_nested(d, keys) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment