3 ms·
def switch(match, dictionary, default="no match"): for key in dictionary.keys(): if match in key: switch.last_match = key
by jpxw 6y ago
def switch(match, dictionary, default="no match"):
for key in dictionary.keys():
if match in key:
switch.last_match = key
return dictionary.get(key)
return default
Using “in” rather than “==“ here seems odd to me, is that intentional?
i.e I’d expect switch(‘abc’, {‘a’: 1}, default=“default”) to return “default”, but under this code it’d return 1, no?
- klyrs 6y agoYou got that containment backwards; switch('a', {'abc': 1}, 'default') #returns 1 ... but you're not wrong, that's godawful. But from the context of the article, they're optimizing for the case where multiple cases evaluate to the same answer. It would make more sense to write switch('a', {('a','b','c'): 1}, 'default') #returns 1 I'd optimize for performance, personally: def switch(match, dictionary, default="no match"): return dictionary.get(match, default)
- Franciscouzo 6y agoIt's not even thread safe.