Skip to content

Instantly share code, notes, and snippets.

@schwartzmx
Created August 25, 2021 22:41
Show Gist options
  • Save schwartzmx/9d98ce2ec01401f9b26415134e791745 to your computer and use it in GitHub Desktop.
Save schwartzmx/9d98ce2ec01401f9b26415134e791745 to your computer and use it in GitHub Desktop.
Dumb, probably unnecessary, helper for looking up a value from a dict for known permutations of a key, or fallback keys. Rather than `dict.get('Key', dict.get('KEY'))` use `get_first(dict, 'Key', 'KEY')` - save yourself 3 keystrokes in the case of 2 keys, more as the # of keys grow! :wow: /s
from typing import Any, Dict, Optional
def get_first(d: Dict[Any, Any], *keys: Any) -> Optional[Any]:
"""Return the first value from d that is not None utilizing the *keys as key lookups.
If no value can be found for any key, returns None.
Example:
>>> d = {
'tesT': 1,
'TeST': 2,
'TEST': 3
}
>>> get_first(d, 'key', 'test', 'TEST', 'tesT')
3
>>> get_first(d, 1, 2, 3)
>>>
"""
for k in keys:
val = d.get(k)
if val is not None:
return val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment