rics.utility.collections.dicts#

Dict utility functions.

Module Attributes

KT

Key type.

VT

Value type.

HVT

Hashable value type.

OKT

Outer key type.

MakeType

Valid input types for making the InheritedKeysDict.make() function.

Functions

compute_if_absent(d, key[, func])

Compute and store key using func if key is not in the dict.

flatten_dict(d[, join_string, filter_predicate])

Flatten a nested dictionary.

reverse_dict(d)

Swap keys and values.

Classes

InheritedKeysDict([specific, default])

A nested dictionary that returns default-backed child dictionaries.

TypeVar(name, *constraints[, bound, ...])

Type variable.

KT#

Key type.

alias of TypeVar(‘KT’, bound=Hashable)

VT#

Value type.

alias of TypeVar(‘VT’)

HVT#

Hashable value type.

alias of TypeVar(‘HVT’, bound=Hashable)

OKT#

Outer key type.

alias of TypeVar(‘OKT’, bound=Hashable)

compute_if_absent(d: Dict[KT, VT], key: KT, func: Optional[Callable[[KT], VT]] = 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 if None.

Returns

The value of k in d.

reverse_dict(d: Mapping[KT, HVT]) Dict[HVT, KT][source]#

Swap keys and values.

Parameters

d – A dict to reverse.

Returns

A reversed copy of d.

Examples

Reversing a dict with two elements.

>>> from rics.utility.collections.dicts import reverse_dict
>>> reverse_dict({"A": 0, "B": 1})
{0: 'A', 1: 'B'}
flatten_dict(d: Dict[str, Any], join_string: str = '.', filter_predicate: Optional[Callable[[str, Any], bool]] = 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 True if the entry should be kept.

Returns

A flattened version of d.

Examples

Flattening a shallow nested dict.

>>> from rics.utility.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: Optional[Dict[OKT, Dict[KT, VT]]] = None, default: Optional[Dict[KT, VT]] = None)[source]#

Bases: Mapping[OKT, Dict[KT, VT]]

A nested dictionary that returns default-backed child dictionaries.

The length of an InheritedKeysDict is equal to the number of specific outer keys, and is considered True when cast to bool if there are shared and/or specific keys present.

Parameters
  • default – Shared (fallback) mappings for all contexts.

  • specific – Context-specific translations, backed by default mappings.

Examples

A short demonstration.

>>> from rics.utility.collections.dicts import InheritedKeysDict
>>> shared = {0: "shared0", 1: "shared1"}
>>> specific = {
... "ctx0": {0: "c0-v0"},
... "ctx1": {0: "c1-v0", 1: "c1-v1"},
... }
>>> d = InheritedKeysDict(default=shared, specific=specific)
>>> d
InheritedKeysDict(default={0: 'shared0', 1: 'shared1'},
specific={'ctx0': {0: 'c0-v0'}, 'ctx1': {0: 'c1-v0', 1: 'c1-v1'}})
>>> d["ctx0"]  # Value of key 0 is inherited
{0: 'c0-v0', 1: 'shared1'}
>>> d["ctx1"]  # Both keys are specified, so nothing is inherited
{0: 'c1-v0', 1: 'c1-v1'}
>>> "not-in-d" in d  # With defaults, all keys are considered as part of d..
True
>>> d["not-in-d"]  # ..but, 'not-in-d' unknowns inherit all keys
{0: 'shared0', 1: 'shared1'}
>>> len(d)  # The length of d is equal to the number of specific contexts
2
copy() InheritedKeysDict[source]#

Make a copy of this InheritedKeysDict.

classmethod make(arg: Union[Dict[str, Union[Dict[KT, VT], Dict[OKT, Dict[KT, VT]]]], InheritedKeysDict[OKT, KT, VT]]) InheritedKeysDict[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.

alias of Union[Dict[str, Union[Dict[KT, VT], Dict[OKT, Dict[KT, VT]]]], InheritedKeysDict[OKT, KT, VT]]