Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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):
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