rics.collections.dicts#
Dict utility functions.
Module Attributes
Key type. |
|
Value type. |
|
Hashable value type. |
|
Outer key type. |
|
Valid input types for making the |
Functions
TypedDict(typename[, fields, total]) |
A simple typed namespace. |
|
Compute and store key using func if key is not in the dict. |
|
Flatten a nested dictionary. |
|
Swap keys and values. |
Classes
ActionLevel(value) |
Action level enumeration type for events. |
|
A nested dictionary that returns default-backed child dictionaries. |
TypeVar(name, *constraints[, bound, ...]) |
Type variable. |
- class VT#
Value type.
alias of TypeVar(‘VT’)
- compute_if_absent(d: Dict[KT, VT], key: KT, func: Callable[[KT], VT] | None = None) VT[source]#
Compute and store key using func if key is not in the dict.
- Parameters:
d – A dict.
key – The key to get.
func – A function to call for missing keys. Perform regular
__getitem__call ifNone.
- Returns:
The value of k in d.
- reverse_dict(d: Mapping[KT, HVT], duplicate_key_action: Literal['ignore', 'warn', 'raise', 'IGNORE', 'WARN', 'RAISE'] | ActionLevel = 'raise') Dict[HVT, KT][source]#
Swap keys and values.
- Parameters:
d – A dict to reverse.
duplicate_key_action – Action to take if the return dict has key collisions in the reversed dict, i.e. there are duplicate values in d. Set to ignore to allow.
- Returns:
A reversed copy of d.
Examples
Reversing a dict with two elements.
>>> from rics.collections.dicts import reverse_dict >>> reverse_dict({"A": 0, "B": 1}) {0: 'A', 1: 'B'}
- Raises:
ValueError – If there are duplicate values in d and
duplicate_key_action='raise'.
- flatten_dict(d: Dict[str, Any], join_string: str = '.', filter_predicate: Callable[[str, Any], bool] | None = None) Dict[str, Any][source]#
Flatten a nested dictionary.
- Parameters:
d – A dict to flatten. Keys must be strings.
join_string – Joiner for nested keys.
filter_predicate – A callable which takes a key and value, returning
Trueif the entry should be kept.
- Returns:
A flattened version of d.
Examples
Flattening a shallow nested dict.
>>> from rics.collections.dicts import flatten_dict >>> flatten_dict({"foo": 0, "bar": {"foo": 1, "bar": 2}}) {'foo': 0, 'bar.foo': 1, 'bar.bar': 2}
- class InheritedKeysDict(specific: Dict[OKT, Dict[KT, VT]] | None = None, default: Dict[KT, VT] | None = None)[source]#
Bases:
Mapping[OKT,Dict[KT,VT]]A nested dictionary that returns default-backed child dictionaries.
The length of an
InheritedKeysDictis equal to the number of specific outer keys, and is consideredTruewhen cast to bool if there are shared and/or specific keys present.- Parameters:
default – Shared (fallback) mappings for all contexts.
specific – Context-specific mappings, backed by the default fallback mappings.
Examples
A short demonstration.
>>> from rics.collections.dicts import InheritedKeysDict >>> shared = {0: 'fallback-for-0', 1: 'fallback-for-1'} >>> specific = { ... 'ctx0': {0: 'c0-v0'}, ... 'ctx1': {0: 'c1-v0', 1: 'c1-v1', 2: 'c1-v2'}, ... } >>> ikd = InheritedKeysDict(default=shared, specific=specific); ikd InheritedKeysDict(default={0: 'fallback-for-0', 1: 'fallback-for-1'}, specific={'ctx0': {0: 'c0-v0'}, 'ctx1': {0: 'c1-v0', 1: 'c1-v1', 2: 'c1-v2'}})
The value of key 0 is inherited for ‘ctx0’. The ‘ctx1’-context defines all shared keys, as well as a unique key.
>>> ikd['ctx0'] {0: 'c0-v0', 1: 'fallback-for-1'} >>> ikd['ctx1'] {0: 'c1-v0', 1: 'c1-v1', 2: 'c1-v2'}
The
InheritedKeysDict.__contains__-method isTruefor all keys. Unknown keys simply return the default values. This will be an empty if no specific keys are specified.>>> 'unseen-key' in ikd True >>> ikd['unseen-key'] {0: 'fallback-for-0', 1: 'fallback-for-1'}
The length of ikd is equal to the number of specific contexts (two in this case).
- classmethod make(arg: InheritedKeysDict[OKT, KT, VT] | _MakeDict) InheritedKeysDict[OKT, KT, VT][source]#
Create instance from a mapping.
The given argument must be on the format:
{ "default": {key: value}, "specific": { ctx0: {key: value}, ctx1: {key: value}, ... ctxN: {key: value}, } }
No other top-level keys are accepted, but neither default nor context-specific are required.
- Parameters:
arg – Input to make an instance from.
- Returns:
A new instance.
- Raises:
ValueError – If there are any keys other than ‘default’ and ‘context-specific’ present in mapping.
- MakeType#
Valid input types for making the
InheritedKeysDict.make()function.