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_get is 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 keys is not in d and no default_value is given

See also

or_replace

will 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_replace will replace the first key value in keys that exists, with value.

Parameters
ddict
keyslist

candidate keys

valuevalue that is set
Returns
outd

Updated dict

Raises
KeyError

If no keys are given

See also

or_get

Returns 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'}