Skip to content

Instantly share code, notes, and snippets.

@sohang3112
Created June 29, 2022 05:41
Show Gist options
  • Save sohang3112/7df025a072aa0e2b6692f3bc01656472 to your computer and use it in GitHub Desktop.
Save sohang3112/7df025a072aa0e2b6692f3bc01656472 to your computer and use it in GitHub Desktop.
Try keys in order on a dict-like object
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