Created
September 25, 2019 21:38
-
-
Save rodmoioliveira/dabcef342d5430ac8d37aa277c2a5d2c to your computer and use it in GitHub Desktop.
Safely Accessing Deeply Nested Values In Python Dictionaries
This file contains hidden or 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
| # 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