Skip to content

Instantly share code, notes, and snippets.

Embed
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 {
"TIMMY_BLACK": {
"item": "Timmy's Coffee Barista's Black",
"sugar_free": True,
"with_milk": False,
},
"TIMMY_LATTE": {
"item": "Timmy's Coffee Latte",
"sugar_free": True,
"with_milk": False,
},
"TIMMY_SWEETENED_LATTE": {
"item": "Timmy's Coffee Latte - Sweetened",
"sugar_free": True,
"with_milk": True,
},
"TIMMY_SIGNATURE_CARAMEL": {
"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"]
coffees.filter(sugar_free_filter)
len(coffees) # 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.