Skip to content

Instantly share code, notes, and snippets.

@aquam8
Created January 27, 2012 02:05
Show Gist options
  • Save aquam8/1686536 to your computer and use it in GitHub Desktop.
Save aquam8/1686536 to your computer and use it in GitHub Desktop.
Dictionary filtering
#!/bin/env python
# keys is a list of key
def filter_keys(keys, object):
return dict((x,y) for (x, y) in object.iteritems() if x in keys)
# or with keys being one or more keys
def filter_keys2(object, *keys):
return dict((x,y) for (x, y) in object.iteritems() if x in keys)
# or with keys being a dictionnary (from another object maybe)
def filter_keys3(object, keys):
return dict((x,y) for (x, y) in object.iteritems() if x in keys.keys())
user_obj = dict( {'name':'matt lohier', 'first':'matt', 'last':'lohier', 'bsb':'12321', 'account':'4565'} )
print filter_keys(['first','last'], user_obj)
print filter_keys2(user_obj, 'first', 'last', 'more_attribute')
print filter_keys2(user_obj, *['first', 'last'])
some_other_dict = dict( {'first':'whocares', 'last':'whocares'} )
print filter_keys3(user_obj, some_other_dict)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment