Created
June 14, 2013 19:55
-
-
Save Flushot/5784760 to your computer and use it in GitHub Desktop.
Subsets a dictionary based on a set of specified keys to include
This file contains 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 subdict(d, include_keys=[]): | |
""" | |
Subsets a :dict: by keys specified in :include_keys: | |
>>> subdict({ 'a': 1, 'b': 2, 'c': 3 }, ['a', 'c']) | |
{ 'a': 1', 'c': 3 } | |
>>> subdict({ 'a': 1, 'b': 2, 'c': 3 }, ['x', 'y']) | |
{} | |
>>> subdict({}, []) | |
{} | |
>>> subdict({}, None) | |
{} | |
>>> subdict(None, []) | |
None | |
""" | |
if d is None: return None | |
if not include_keys: return {} | |
ret = {} | |
for key in d.iterkeys(): | |
if key in include_keys: | |
ret[key] = d[key] | |
return ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment