Skip to content

Dict

Bases: PyoMutableMapping[K, V]

A Dict is a key-value store similar to Python's built-in dict, but with additional methods inspired by Rust's HashMap.

Accept the same input types as the built-in dict, including Mapping, Iterable of key-value pairs, and objects implementing __getitem__() and keys().

Implement the MutableMapping interface, so all standard dictionary operations are supported.

Tip

Prefer using Dict.from_ref when wrapping existing dictionaries to avoid unnecessary copying.

Parameters:

Name Type Description Default
data DictConvertible[K, V]

Initial data for the Dict that can converted to a dictionary.

required

Example:

>>> import pyochain as pc
>>> dict_obj = pc.Dict({1: "a", 2: "b"})
>>> dict_obj
Dict(1: 'a', 2: 'b')
>>> dict_obj.get_item(1)
Some('a')
>>> dict_obj.items().iter().collect()
Seq((1, 'a'), (2, 'b'))

Source code in src/pyochain/_dict.py
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
class Dict[K, V](PyoMutableMapping[K, V]):
    """A `Dict` is a key-value store similar to Python's built-in `dict`, but with additional methods inspired by Rust's `HashMap`.

    Accept the same input types as the built-in `dict`, including `Mapping`, `Iterable` of key-value pairs, and objects implementing `__getitem__()` and `keys()`.

    Implement the `MutableMapping` interface, so all standard dictionary operations are supported.

    Tip:
        Prefer using `Dict.from_ref` when wrapping existing dictionaries to avoid unnecessary copying.

    Args:
        data (DictConvertible[K, V]): Initial data for the Dict that can converted to a dictionary.

    Example:
    ```python
    >>> import pyochain as pc
    >>> dict_obj = pc.Dict({1: "a", 2: "b"})
    >>> dict_obj
    Dict(1: 'a', 2: 'b')
    >>> dict_obj.get_item(1)
    Some('a')
    >>> dict_obj.items().iter().collect()
    Seq((1, 'a'), (2, 'b'))

    ```
    """

    __slots__ = ("_inner",)
    _inner: dict[K, V]

    def __init__(self, data: DictConvertible[K, V]) -> None:
        self._inner = dict(data)

    def __repr__(self) -> str:
        from pprint import pformat

        return (
            f"{self.__class__.__name__}({pformat(self._inner, sort_dicts=False)[1:-1]})"
        )

    def __iter__(self) -> Iterator[K]:
        return iter(self._inner)

    def __len__(self) -> int:
        return len(self._inner)

    def __getitem__(self, key: K) -> V:
        return self._inner[key]

    def __setitem__(self, key: K, value: V) -> None:
        self._inner[key] = value

    def __delitem__(self, key: K) -> None:
        del self._inner[key]

    @staticmethod
    def from_ref[K1, V1](data: dict[K1, V1]) -> Dict[K1, V1]:
        """Wrap an existing `dict` without copying.

        This is the recommended way to create a `Dict` from foreign functions that return a standard Python `dict`.

        Warning:
            Any modifications made to this `Dict` will also affect the original, and vice versa.

        Args:
            data (dict[K1, V1]): The dictionary to wrap.

        Returns:
            Dict[K1, V1]: A new `Dict` instance wrapping the provided dictionary.

        Example:
        ```python
        >>> import pyochain as pc
        >>> original_dict = {1: "a", 2: "b", 3: "c"}
        >>> dict_obj = pc.Dict.from_ref(original_dict)
        >>> dict_obj
        Dict(1: 'a', 2: 'b', 3: 'c')
        >>> dict_obj.insert(1, "z")
        Some('a')
        >>> original_dict
        {1: 'z', 2: 'b', 3: 'c'}

        ```
        """
        instance: Dict[K1, V1] = Dict.__new__(Dict)  # pyright: ignore[reportUnknownVariableType]
        instance._inner = data
        return instance

    @staticmethod
    def from_kwargs[U](**kwargs: U) -> Dict[str, U]:
        """Create a `Dict` from keyword arguments.

        Args:
            **kwargs (U): Key-value pairs to initialize the Dict.

        Returns:
            Dict[str, U]: A new Dict instance containing the provided key-value pairs.

        Example:
        ```python
        >>> import pyochain as pc
        >>> pc.Dict.from_kwargs(a=1, b=2)
        Dict('a': 1, 'b': 2)

        ```
        """
        return Dict.from_ref(kwargs)

    @staticmethod
    def from_object(obj: object) -> Dict[str, Any]:
        """Create a `Dict` from an object `__dict__` attribute.

        We can't know in advance the values types, so we use `Any`.

        Args:
            obj (object): The object whose `__dict__` attribute will be used to create the Dict.

        Returns:
            Dict[str, Any]: A new Dict instance containing the attributes of the object.

        Example:
        ```python
        >>> import pyochain as pc
        >>> class Person:
        ...     def __init__(self, name: str, age: int):
        ...         self.name = name
        ...         self.age = age
        >>> person = Person("Alice", 30)
        >>> pc.Dict.from_object(person)
        Dict('name': 'Alice', 'age': 30)

        ```
        """
        return Dict.from_ref(obj.__dict__)

from_kwargs(**kwargs) staticmethod

Create a Dict from keyword arguments.

Parameters:

Name Type Description Default
**kwargs U

Key-value pairs to initialize the Dict.

{}

Returns:

Type Description
Dict[str, U]

Dict[str, U]: A new Dict instance containing the provided key-value pairs.

Example:

>>> import pyochain as pc
>>> pc.Dict.from_kwargs(a=1, b=2)
Dict('a': 1, 'b': 2)

Source code in src/pyochain/_dict.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
@staticmethod
def from_kwargs[U](**kwargs: U) -> Dict[str, U]:
    """Create a `Dict` from keyword arguments.

    Args:
        **kwargs (U): Key-value pairs to initialize the Dict.

    Returns:
        Dict[str, U]: A new Dict instance containing the provided key-value pairs.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Dict.from_kwargs(a=1, b=2)
    Dict('a': 1, 'b': 2)

    ```
    """
    return Dict.from_ref(kwargs)

from_object(obj) staticmethod

Create a Dict from an object __dict__ attribute.

We can't know in advance the values types, so we use Any.

Parameters:

Name Type Description Default
obj object

The object whose __dict__ attribute will be used to create the Dict.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A new Dict instance containing the attributes of the object.

Example:

>>> import pyochain as pc
>>> class Person:
...     def __init__(self, name: str, age: int):
...         self.name = name
...         self.age = age
>>> person = Person("Alice", 30)
>>> pc.Dict.from_object(person)
Dict('name': 'Alice', 'age': 30)

Source code in src/pyochain/_dict.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
@staticmethod
def from_object(obj: object) -> Dict[str, Any]:
    """Create a `Dict` from an object `__dict__` attribute.

    We can't know in advance the values types, so we use `Any`.

    Args:
        obj (object): The object whose `__dict__` attribute will be used to create the Dict.

    Returns:
        Dict[str, Any]: A new Dict instance containing the attributes of the object.

    Example:
    ```python
    >>> import pyochain as pc
    >>> class Person:
    ...     def __init__(self, name: str, age: int):
    ...         self.name = name
    ...         self.age = age
    >>> person = Person("Alice", 30)
    >>> pc.Dict.from_object(person)
    Dict('name': 'Alice', 'age': 30)

    ```
    """
    return Dict.from_ref(obj.__dict__)

from_ref(data) staticmethod

Wrap an existing dict without copying.

This is the recommended way to create a Dict from foreign functions that return a standard Python dict.

Warning

Any modifications made to this Dict will also affect the original, and vice versa.

Parameters:

Name Type Description Default
data dict[K1, V1]

The dictionary to wrap.

required

Returns:

Type Description
Dict[K1, V1]

Dict[K1, V1]: A new Dict instance wrapping the provided dictionary.

Example:

>>> import pyochain as pc
>>> original_dict = {1: "a", 2: "b", 3: "c"}
>>> dict_obj = pc.Dict.from_ref(original_dict)
>>> dict_obj
Dict(1: 'a', 2: 'b', 3: 'c')
>>> dict_obj.insert(1, "z")
Some('a')
>>> original_dict
{1: 'z', 2: 'b', 3: 'c'}

Source code in src/pyochain/_dict.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
@staticmethod
def from_ref[K1, V1](data: dict[K1, V1]) -> Dict[K1, V1]:
    """Wrap an existing `dict` without copying.

    This is the recommended way to create a `Dict` from foreign functions that return a standard Python `dict`.

    Warning:
        Any modifications made to this `Dict` will also affect the original, and vice versa.

    Args:
        data (dict[K1, V1]): The dictionary to wrap.

    Returns:
        Dict[K1, V1]: A new `Dict` instance wrapping the provided dictionary.

    Example:
    ```python
    >>> import pyochain as pc
    >>> original_dict = {1: "a", 2: "b", 3: "c"}
    >>> dict_obj = pc.Dict.from_ref(original_dict)
    >>> dict_obj
    Dict(1: 'a', 2: 'b', 3: 'c')
    >>> dict_obj.insert(1, "z")
    Some('a')
    >>> original_dict
    {1: 'z', 2: 'b', 3: 'c'}

    ```
    """
    instance: Dict[K1, V1] = Dict.__new__(Dict)  # pyright: ignore[reportUnknownVariableType]
    instance._inner = data
    return instance