Created
November 17, 2015 18:12
-
-
Save noahlt/c9d4cd06e205d290f03d to your computer and use it in GitHub Desktop.
Pick keys/values from dict
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
| 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