Created
June 29, 2022 05:41
-
-
Save sohang3112/7df025a072aa0e2b6692f3bc01656472 to your computer and use it in GitHub Desktop.
Try keys in order on a dict-like object
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 Mapping | |
def try_keys(obj: Mapping, *keys, default_value=None): | |
""" | |
Tries each given key (in order) on obj (a dict-like object) and | |
returns value of first key found in object. If no key is found in object, | |
then it returns default_value. | |
>>> try_keys({'a': 1}, 'a', 'b', default_value=0) | |
1 | |
>>> try_keys({'b': 3}, 'a', 'b', default_value=0) | |
3 | |
>>> try_keys({'d': -1, 'e': 10}, 'a', 'b', default_value=0) | |
0 | |
""" | |
for key in keys: | |
if key in obj: | |
return obj[key] | |
return default_value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment