Last active
August 29, 2015 14:13
-
-
Save richard-mihalovic/e19974a1e05d64f1b436 to your computer and use it in GitHub Desktop.
Read value in Python dict and checks if keys exists.
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 dict_read_value(src, path, default=None): | |
value = src | |
keys = path.split('.') | |
for key in keys: | |
if isinstance(value, dict) and key in value: | |
value = value[key] | |
else: | |
return default | |
return value | |
# test | |
d = {'x': {'y': {'z': 1}}} | |
assert dict_read_value(d, 'x.y.z') == 1 | |
assert dict_read_value(d, 'x.x', -1) == -1 | |
assert dict_read_value(d, 'a.b.c', 0) == 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Zmenil som type(value) == dict -> isinstance(value, dict).
Tu je vysvetlene preco je lepsie pouzit isinstance: http://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python .