Skip to content

Instantly share code, notes, and snippets.

@correl
Last active April 12, 2017 14:59
Show Gist options
  • Save correl/1f5458e1dce82a9cfb0d8dd5a22230e5 to your computer and use it in GitHub Desktop.
Save correl/1f5458e1dce82a9cfb0d8dd5a22230e5 to your computer and use it in GitHub Desktop.
Recursively accessing dictionaries and sorting a list of nested data structures
from functools import partial
def recursiveitemgetter(keys):
"""Returns a function that recursively fetches a value from a
dictionary, where keys is a list of keys to traverse."""
def recursive_get(keys, dictionary):
"""Recursively fetches a value from a dictionary, where keys is a
list of keys to traverse."""
return reduce(lambda acc, i: acc.get(i), keys, dictionary)
return partial(recursive_get, keys)
# Example: Sorting a list of dictionaries by arbitrarily nested keys
dicts = [
{'foo': {'bar': 123}, 'baz': 1},
{'foo': {'bar': 111}, 'baz': 5},
{'foo': {'bar': 234}, 'baz': 3},
{'foo': {'bar': 555}, 'baz': 2},
{'foo': {'bar': 411}, 'baz': 8},
]
sorted_by_bar = sorted(dicts, key=recursiveitemgetter(['foo', 'bar']))
sorted_by_baz = sorted(dicts, key=recursiveitemgetter(['baz']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment