Skip to content

Instantly share code, notes, and snippets.

@noahlt
Created November 17, 2015 18:12
Show Gist options
  • Save noahlt/c9d4cd06e205d290f03d to your computer and use it in GitHub Desktop.
Save noahlt/c9d4cd06e205d290f03d to your computer and use it in GitHub Desktop.
Pick keys/values from dict
def pick(d, filter_tree):
'''Returns a new dictionary by picking keys/values from d per filter_tree.
Works recursively: values in filter_tree can be either True or dictionaries
which are their own filters.
>>> d = {'a': 1, 'b': 2, 'c': {'foo': -1, 'bar': -2}, 'd': {'r': 'red', 'b': 'blue'}}
>>> pick(d, {'a': True, 'b': True})
{'a': 1, 'b': 2}
>>> pick(d, {'a': True, 'b': True, 'd': True})
{'a': 1, 'b': 2, 'd': {'r': 'red', 'b': 'blue'}}
>>> pick(d, {'a': True, 'b': True, 'd': {'r': True}})
{'a': 1, 'b': 2, 'd': {'r': 'red'}}
'''
r = {}
for k, filter_branch in filter_tree.items():
if isinstance(filter_branch, dict):
r[k] = pick(d[k], filter_branch)
elif filter_branch is True:
r[k] = d[k]
return r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment