Skip to content

Instantly share code, notes, and snippets.

@richard-mihalovic
Last active August 29, 2015 14:13
Show Gist options
  • Save richard-mihalovic/e19974a1e05d64f1b436 to your computer and use it in GitHub Desktop.
Save richard-mihalovic/e19974a1e05d64f1b436 to your computer and use it in GitHub Desktop.
Read value in Python dict and checks if keys exists.
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
@richard-mihalovic
Copy link
Author

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 .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment