Created
October 4, 2016 12:57
-
-
Save thomasvnl/68729da1da0afc138851dd247d7c1de4 to your computer and use it in GitHub Desktop.
Get and set values by passing in a multilevel key, a data dictionary, and in case of setting also a value
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 get_value_by_multilevel_key(key, data): | |
""" | |
returns a value by a multilevel key reference e.g. 'object.foo.bar' as key returns the value 10 | |
(see below) | |
{ | |
object: { | |
foo: | |
bar: 10 | |
} | |
} | |
} | |
:param key: | |
:param data: | |
:return: | |
""" | |
key = key.split(".") | |
reference = None | |
for item in key: | |
try: | |
if reference is not None: | |
reference = reference[item] | |
else: | |
reference = data[item] | |
except (AttributeError, KeyError): | |
return None | |
return reference | |
def set_value_by_multilevel_key(key, data, value): | |
""" | |
Sets the value of a multilevel key reference in the data object | |
:param key: | |
:param data: | |
:param value: | |
:return: | |
""" | |
# Making sure that a single level key doesn't destroy the logic and also | |
# does what one would expect | |
if len(key.split(".")) == 1: | |
data[key] = value | |
return data | |
head, tail = key.rsplit(".", 1) | |
get_value_by_multilevel_key(head, data)[tail] = value | |
return data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment