Skip to content

Instantly share code, notes, and snippets.

@hassanrazahasrat
Last active October 26, 2023 20:18
Show Gist options
  • Save hassanrazahasrat/9f42dc4afc9bd50c61664ee170b2940d to your computer and use it in GitHub Desktop.
Save hassanrazahasrat/9f42dc4afc9bd50c61664ee170b2940d to your computer and use it in GitHub Desktop.
Python nested dict deep get utility method

Python dictionary utility method to get nested values

Supports nested dict, list within a dict

Usage Example:

data = {
  'name': 'Hassan',
  'detail': {
    'country': 'Pakistan',
    'hobbies': [
      'cricket',
      'gaming'
    ]
  }
}

print(dict_deep_get(data, 'name')) # Hassan
print(dict_deep_get(data, 'detail.country')) # Pakistan
print(dict_deep_get(data, 'detail.hobbies.1')) # gaming

print(dict_deep_get(data, 'detail.city')) # None
print(dict_deep_get(data, 'detail.hobbies.2', 'N/A')) # N/A

The time complexity of this function is O(n) where n is the number of iterations. Space complexity is O(1)

from functools import reduce
def dict_deep_get(dictionary, keys, default=None):
return reduce(
lambda d,
key: d.get(
key,
default,
) if isinstance(d, dict) else d[int(key)] if isinstance(d, list) and len(d) > int(key) else default,
keys.split("."),
dictionary
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment