Skip to content

collections

Custom data structures.

Classes

FlattenKeyDictView

FlattenKeyDictView(
    *args, flat_key_separator: str = ".", **kwargs
)

Bases: dict

Dictionary view which works with flatten keys.

This class allows accessing values of a normal Python nested dictionary using flatten keys, e.g. a.b.c, parent.child. The dictionary view implements getting, setting, deleting and checking existance of keys.

Example usage:

from ipsl_common.collections import FlattenKeyDictView

d = {
    "a": {
        "k1": 1,
        "k2": 2
    }
}
fd = FlattenKeyDictView(d)
fd["a.k1"] = 17
del fd["a.k2"]
fd["b.k1"] = 34
print(fd)

Which prints the following result:

{'a': {'k1': 17}, 'b': {'k1': 34}}

Create flatten-key dict view class.

Parameters:

  • *args

    positional arguments passed to the dict() constructor

  • flat_key_separator

    (str, default: '.' ) –

    separator of keys in the flat key (default: .)

  • **kwargs

    keyword arguments passed to the dict() constructor

Source code in ipsl_common/collections.py
34
35
36
37
38
39
40
41
42
43
def __init__(self, *args, flat_key_separator: str = ".", **kwargs) -> None:
    """Create flatten-key dict view class.

    Args:
        *args: positional arguments passed to the dict() constructor
        flat_key_separator: separator of keys in the flat key (default: `.`)
        **kwargs: keyword arguments passed to the dict() constructor
    """
    self.flat_key_separator = flat_key_separator
    super().__init__(*args, **kwargs)

Attributes

flat_key_separator instance-attribute
flat_key_separator = flat_key_separator

Methods:

__contains__
__contains__(flat_key: object) -> bool

Check if flat key exists

Source code in ipsl_common/collections.py
68
69
70
71
72
73
74
75
76
def __contains__(self, flat_key: object) -> bool:
    """Check if flat key exists"""
    if not isinstance(flat_key, str):
        raise TypeError(f"Flat key must be a str, and not: {flat_key}")
    try:
        parent, last = self._resolve_parent(flat_key)
        return dict.__contains__(parent, last)
    except KeyError:
        return False
__delitem__
__delitem__(flat_key: str) -> None

Delete key-value pairs using flat key

Source code in ipsl_common/collections.py
63
64
65
66
def __delitem__(self, flat_key: str) -> None:
    """Delete key-value pairs using flat key"""
    parent, last = self._resolve_parent(flat_key)
    dict.__delitem__(parent, last)
__getitem__
__getitem__(flat_key: str) -> Any

Retrieve value using flat key

Source code in ipsl_common/collections.py
53
54
55
56
def __getitem__(self, flat_key: str) -> Any:
    """Retrieve value using flat key"""
    parent, last = self._resolve_parent(flat_key)
    return dict.__getitem__(parent, last)
__setitem__
__setitem__(flat_key: str, value: Any) -> None

Set new value using flat key

Source code in ipsl_common/collections.py
58
59
60
61
def __setitem__(self, flat_key: str, value: Any) -> None:
    """Set new value using flat key"""
    parent, last = self._resolve_parent(flat_key, create_if_missing=True)
    dict.__setitem__(parent, last, value)
ordered_keys
ordered_keys() -> list[str]

Ordered list of all flatten keys (including all parent keys)

Source code in ipsl_common/collections.py
45
46
47
def ordered_keys(self) -> list[str]:
    """Ordered list of all flatten keys (including all parent keys)"""
    return self._flatten_keys(self)
ordered_leaf_keys
ordered_leaf_keys() -> list[str]

Ordered list of flatten leaf keys (excluding all parent keys)

Source code in ipsl_common/collections.py
49
50
51
def ordered_leaf_keys(self) -> list[str]:
    """Ordered list of flatten leaf keys (excluding all parent keys)"""
    return self._flatten_keys(self, only_leafs=True)