Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Filtering Dictionary in Python
from typing import Dict
# Helper function to generate dict object
def get_menu() -> Dict[str, dict]:
return {
"item": "Timmy's Coffee Barista's Black",
"sugar_free": True,
"with_milk": False,
"item": "Timmy's Coffee Latte",
"sugar_free": True,
"with_milk": False,
"item": "Timmy's Coffee Latte - Sweetened",
"sugar_free": True,
"with_milk": True,
"item": "Timmy's Signature - Caramel Latte",
"sugar_free": None, # Unknown
"with_milk": True,
# Our dict subclass
class FilterableDict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
def filter(self, predicate):
key_copy = tuple(self.keys())
for k in key_copy:
if predicate(k, self.get(k)):
del self[k]
return self
def __repr__(self):
return "FilterableDict({})".format(super().__repr__())
coffees = FilterableDict(get_menu())
coffees # FilterableDict({...})
len(coffees) # 4
sugar_free_filter = lambda _, v: not v["sugar_free"]
len(coffees) # 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment