Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@HonzaKral

This comment has been minimized.

HonzaKral commented Jan 18, 2015

neni potreba pouzivat get() kdyz vis, ze tam ten klic je, pro genericke pripady (tebe se asi netyka) by mohlo byt fajn overit ze value je dict predtim nez do nej pristoupim (radek 6)

@richard-mihalovic

This comment has been minimized.

Owner

richard-mihalovic commented Jan 18, 2015

To dava zmysel, zmenil som to ...

neni potreba pouzivat get() kdyz vis, ze tam ten klic je, pro genericke pripady (tebe se asi netyka) by mohlo byt fajn overit ze value je dict predtim nez do nej pristoupim (radek 6)

@HonzaKral

This comment has been minimized.

HonzaKral commented Jan 18, 2015

jen detail - na kontrolu typu nepouzivej porovnani ale radsi isinstance

@richard-mihalovic

This comment has been minimized.

Owner

richard-mihalovic commented Jan 18, 2015

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