Miscellaneous functions#
- or_get(d: dict, keys: list, default_value=None) Any#
Returns the value from dict based on first match of candidate keys.
or_getis useful when you are not sure exactly how the keys looks like. You pass a list of candidate keys. The first that matches will be returned.- Parameters
- ddict
- keyslist of candidate keys
- default_valuevalue that is returned if no key matches (and default is not None)
- Returns
- outvalue of d[k]
- Raises
- KeyError
If any key in
keysis not indand nodefault_valueis given
See also
or_replacewill replace the first key value in keys that exists, with
value.
Examples
>>> d = dict((("a", 1), ("b", 2))) >>> keys = ["1", "a"] >>> or_get(d, keys) 1
>>> d = dict((("a", 1), ("b", 2))) >>> keys = ["b", "a"] >>> or_get(d, keys) 2
>>> d = dict((("a", 1), ("b", 2))) >>> keys = [1] >>> default_value = 0 >>> or_get(d, keys, default_value) 0
- or_replace(d: dict, keys: list, value: Any)#
or_replacewill replace the first key value in keys that exists, withvalue.- Parameters
- ddict
- keyslist
candidate keys
- valuevalue that is set
- Returns
- outd
Updated dict
- Raises
- KeyError
If no
keysare given
See also
or_getReturns the value from dict based on first match of candidate keys.
Examples
>>> d = dict((("a", 1), ("b", 2))) >>> keys = ["1", "a"] >>> value = "1" >>> or_replace(d, keys, value) {'a': '1', 'b': 2}
>>> d = dict((("a", 1), ("b", 2))) >>> keys = ["b", "a"] >>> value = "1" >>> or_replace(d, keys, value) {'a': 1, 'b': '1'}