Skip to content

Instantly share code, notes, and snippets.

@rondreas
Created March 8, 2016 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rondreas/fd8050f82743effa9841 to your computer and use it in GitHub Desktop.
Save rondreas/fd8050f82743effa9841 to your computer and use it in GitHub Desktop.
Filter Dictionary List
#!/usr/bin/env python3
def filter(listInput, **kwargs):
''' Searches list of dictionaries for matches to
all key value pairs expressed as key='value' '''
sortedList = []
for dictionary in listInput:
matches = 0
for key, value in kwargs.items():
if dictionary[key] == value:
matches += 1
if matches == len(kwargs):
sortedList.append(dictionary)
return sortedList
if __name__ == '__main__':
listOfDicts = [{'date':'2012-12-24', 'dinner':'ham', 'cupsOfCoffee':6},
{'date':'2016-05-01', 'dinner':'moose', 'cupsOfCoffee':4},
{'date':'2014-11-14', 'dinner':'moose', 'cupsOfCoffee':6}]
print(filter(listOfDicts, dinner='moose', cupsOfCoffee=6))
print(filter(listOfDicts, cupsOfCoffee=6))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment