Skip to content

Instantly share code, notes, and snippets.

@Flushot
Created June 14, 2013 19:55
Show Gist options
  • Save Flushot/5784760 to your computer and use it in GitHub Desktop.
Save Flushot/5784760 to your computer and use it in GitHub Desktop.
Subsets a dictionary based on a set of specified keys to include
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