Last active
September 26, 2020 15:25
-
-
Save melvinkcx/8c8520a27b73dfc04a530221c1f6ff4a to your computer and use it in GitHub Desktop.
Filtering Dictionary in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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