Skip to content

Instantly share code, notes, and snippets.

@rodmoioliveira
Created September 25, 2019 21:38
Show Gist options
  • Select an option

  • Save rodmoioliveira/dabcef342d5430ac8d37aa277c2a5d2c to your computer and use it in GitHub Desktop.

Select an option

Save rodmoioliveira/dabcef342d5430ac8d37aa277c2a5d2c to your computer and use it in GitHub Desktop.
Safely Accessing Deeply Nested Values In Python Dictionaries
# inspirado em https://clojuredocs.org/clojure.core/get-in
from functools import reduce
from numbers import Number
my_dict = {
"username": "rodmoi",
"profile": {
"name": "Rodolfo Oliveira",
"hobbies": ["programming", "chess"],
"address": {
"city": "Rio de Janeiro",
"state": "RJ"
}
}
}
def get_in(dict, path, fallback=None):
'''
Funcionalidade para acessar propriedades dentro de um
dicionário
'''
check_range = lambda acc, cur: acc[cur] if len(acc) > cur - 1 else None
reducer = lambda acc, cur: check_range(acc, cur) if isinstance(cur, Number) else acc.get(cur, fallback)
return reduce(reducer, path, dict)
print(
get_in(my_dict, ['username']),
# => rodmoi
get_in(my_dict, ['profile', 'address', 'city']),
# => Rio de Janeiro
get_in(my_dict, ['profile', 'address', 'zipcode']),
# => None
get_in(my_dict, ['profile', 'hobbies', 0]),
# => programming
get_in(my_dict, ['profile', 'hobbies', 1]),
# => chess
get_in(my_dict, ['profile', 'hobbies', 3]),
# => None
get_in(my_dict, ['profile', 'address', 'zipcode'], '15445-78')
# => 15445-78
)
# https://repl.it/@rodmoioliveira/Save-Acess-to-Dictionaries
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment