Skip to content

Dict

Bases: PyoMutableMapping[K, V]


              flowchart TD
              pyochain._dict.Dict[Dict]
              pyochain.abc._mappings.PyoMutableMapping[PyoMutableMapping]
              pyochain.abc._mappings.PyoMapping[PyoMapping]
              pyochain.abc._collection.PyoCollection[PyoCollection]
              pyochain.abc._iterable.PyoIterable[PyoIterable]
              pyochain.rs.Fluent[Fluent]
              pyochain.rs.Pipe[Pipe]
              pyochain.rs.Tap[Tap]
              pyochain.rs.Checkable[Checkable]
              pyochain.abc._collection.PyoContainer[PyoContainer]
              pyochain.abc._collection.PyoSized[PyoSized]

                              pyochain.abc._mappings.PyoMutableMapping --> pyochain._dict.Dict
                                pyochain.abc._mappings.PyoMapping --> pyochain.abc._mappings.PyoMutableMapping
                                pyochain.abc._collection.PyoCollection --> pyochain.abc._mappings.PyoMapping
                                pyochain.abc._iterable.PyoIterable --> pyochain.abc._collection.PyoCollection
                                pyochain.rs.Fluent --> pyochain.abc._iterable.PyoIterable
                                pyochain.rs.Pipe --> pyochain.rs.Fluent
                
                pyochain.rs.Tap --> pyochain.rs.Fluent
                

                pyochain.rs.Checkable --> pyochain.abc._iterable.PyoIterable
                

                pyochain.abc._collection.PyoContainer --> pyochain.abc._collection.PyoCollection
                
                pyochain.abc._collection.PyoSized --> pyochain.abc._collection.PyoCollection
                





              click pyochain._dict.Dict href "" "pyochain._dict.Dict"
              click pyochain.abc._mappings.PyoMutableMapping href "" "pyochain.abc._mappings.PyoMutableMapping"
              click pyochain.abc._mappings.PyoMapping href "" "pyochain.abc._mappings.PyoMapping"
              click pyochain.abc._collection.PyoCollection href "" "pyochain.abc._collection.PyoCollection"
              click pyochain.abc._iterable.PyoIterable href "" "pyochain.abc._iterable.PyoIterable"
              click pyochain.rs.Fluent href "" "pyochain.rs.Fluent"
              click pyochain.rs.Pipe href "" "pyochain.rs.Pipe"
              click pyochain.rs.Tap href "" "pyochain.rs.Tap"
              click pyochain.rs.Checkable href "" "pyochain.rs.Checkable"
              click pyochain.abc._collection.PyoContainer href "" "pyochain.abc._collection.PyoContainer"
              click pyochain.abc._collection.PyoSized href "" "pyochain.abc._collection.PyoSized"
            

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.

Parameters:

Name Type Description Default
data DictConvertible[K, V]

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

required
See Also
Example

The most straightforward way to create a Dict is from a standard Python dict.

This will copy the data, just like the built-in dict constructor.

>>> from pyochain import Dict
>>> py_dict = {1: "a", 2: "b"}
>>> pyochain_dict = Dict(py_dict)
>>> pyochain_dict
Dict(1: 'a', 2: 'b')
Another common case is when you have an iterable of key-value pairs, such as the one returned by dict::items, or an Iterator of tuples.
>>> from pyochain import Dict, Iter, Seq
>>>
>>> names = ("alice", "bob", "charlie", "dave")
>>> ages = (30, 25, 35, 40)
>>> records = Iter(names).zip(ages).collect(Dict)
>>> records
Dict('alice': 30, 'bob': 25, 'charlie': 35, 'dave': 40)
>>> records.items().iter().collect(Seq)
Seq(('alice', 30), ('bob', 25), ('charlie', 35), ('dave', 40))
Any object that implements the Mapping protocol can also be directly converted to a Dict:
>>> from collections.abc import Mapping
>>> from dataclasses import dataclass
>>> @dataclass
... class CustomMapping(Mapping[int, str]):
...     data: dict[int, str]
...
...     def __getitem__(self, key: int) -> str:
...         return self.data[key]
...
...     def __iter__(self) -> Iterator[int]:
...         return iter(self.data)
...
...     def __len__(self) -> int:
...         return len(self.data)
>>> custom_mapping = CustomMapping({1: "a", 2: "b"})
>>> Dict(custom_mapping)
Dict(1: 'a', 2: 'b')
But it can also be as minimal as an object that implements __getitem__ and keys:
>>> from pyochain import Dict
>>>
>>> class MinimalDictLike:
...     def __init__(self, data: dict[int, str]) -> None:
...         self._data = data
...
...     def keys(self) -> Iterable[int]:
...         return iter(self._data)
...
...     def __getitem__(self, key: int) -> str:
...         return self._data[key]
>>>
>>> minimal_dict_like = MinimalDictLike({1: "a", 2: "b"})
>>> Dict(minimal_dict_like)
Dict(1: 'a', 2: 'b')

Source code in src/pyochain/_dict.py
 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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
class Dict[K, V](PyoMutableMapping[K, V]):  # noqa: PLW1641
    """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.

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

    See Also:
        - [`Dict::from_ref`][from_ref]: Create a `Dict` from an existing dictionary, no-copy.
        - [`Dict::from_kwargs`][from_kwargs]: Create a `Dict` from keyword arguments.
        - [`Dict::from_object`][from_object]: Create a `Dict` from an object's `__dict__` attribute, no-copy.

    Example:
        The most straightforward way to create a `Dict` is from a standard Python `dict`.

        This will copy the data, just like the built-in `dict` constructor.
        ```python
        >>> from pyochain import Dict
        >>> py_dict = {1: "a", 2: "b"}
        >>> pyochain_dict = Dict(py_dict)
        >>> pyochain_dict
        Dict(1: 'a', 2: 'b')

        ```
        Another common case is when you have an iterable of key-value pairs, such as the one returned by `dict::items`, or an `Iterator` of tuples.
        ```python
        >>> from pyochain import Dict, Iter, Seq
        >>>
        >>> names = ("alice", "bob", "charlie", "dave")
        >>> ages = (30, 25, 35, 40)
        >>> records = Iter(names).zip(ages).collect(Dict)
        >>> records
        Dict('alice': 30, 'bob': 25, 'charlie': 35, 'dave': 40)
        >>> records.items().iter().collect(Seq)
        Seq(('alice', 30), ('bob', 25), ('charlie', 35), ('dave', 40))

        ```
        Any object that implements the `Mapping` protocol can also be directly converted to a `Dict`:
        ```python
        >>> from collections.abc import Mapping
        >>> from dataclasses import dataclass
        >>> @dataclass
        ... class CustomMapping(Mapping[int, str]):
        ...     data: dict[int, str]
        ...
        ...     def __getitem__(self, key: int) -> str:
        ...         return self.data[key]
        ...
        ...     def __iter__(self) -> Iterator[int]:
        ...         return iter(self.data)
        ...
        ...     def __len__(self) -> int:
        ...         return len(self.data)
        >>> custom_mapping = CustomMapping({1: "a", 2: "b"})
        >>> Dict(custom_mapping)
        Dict(1: 'a', 2: 'b')

        ```
        But it can also be as minimal as an object that implements `__getitem__` and `keys`:
        ```python
        >>> from pyochain import Dict
        >>>
        >>> class MinimalDictLike:
        ...     def __init__(self, data: dict[int, str]) -> None:
        ...         self._data = data
        ...
        ...     def keys(self) -> Iterable[int]:
        ...         return iter(self._data)
        ...
        ...     def __getitem__(self, key: int) -> str:
        ...         return self._data[key]
        >>>
        >>> minimal_dict_like = MinimalDictLike({1: "a", 2: "b"})
        >>> Dict(minimal_dict_like)
        Dict(1: 'a', 2: 'b')

        ```
    """

    __slots__ = ("_inner",)  # pyright: ignore[reportUnannotatedClassAttribute, reportIncompatibleUnannotatedOverride]
    _inner: dict[K, V]

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

    @classmethod
    def from_keys[K1, V1](cls, keys: Iterable[K1], value: V1 = None) -> Dict[K1, V1]:
        """Create a `Dict` from an iterable of keys, all mapped to the same value.

        This is the equivalent of `dict.fromkeys`, but returns a `Dict` instance.

        Args:
            keys (Iterable[K1]): An iterable of keys to include in the mapping.
            value (V1): The value that each key will be mapped to.

        Returns:
            Dict[K1, V1]: A new `PyoMapping` instance containing the specified keys and value.

        Example:
            ```python
            >>> from pyochain import Dict
            >>> Dict.from_keys([1, 2, 3], "a")
            Dict(1: 'a', 2: 'a', 3: 'a')
            >>> Dict.from_keys("abc")
            Dict('a': None, 'b': None, 'c': None)

            ```
        """
        return cls.from_ref(dict.fromkeys(keys, value))

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

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

    @property
    @no_doctest
    def inner(self) -> dict[K, V]:
        """Get the underlying `dict` data structure.

        Useful when interoperating with functions that require a standard Python `dict`.

        Returns:
            dict[K, V]: The underlying dictionary.
        """
        return self._inner

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

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

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

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

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

    @override
    def __eq__(self, other: object) -> bool:
        match other:
            case Dict():
                return self._inner == other._inner  # pyright: ignore[reportUnknownMemberType]
            case dict():
                return self._inner == other
            case _:
                return False

    @staticmethod
    def from_ref[K1, V1](data: dict[K1, V1]) -> Dict[K1, V1]:
        """Wrap an existing Python builtin `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 data structure, 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
            >>> from pyochain import Dict
            >>> original_dict = {1: "a", 2: "b", 3: "c"}
            >>> ref_dict = Dict.from_ref(original_dict)
            >>> ref_dict
            Dict(1: 'a', 2: 'b', 3: 'c')
            >>> ref_dict.insert(1, "z")
            Some('a')
            >>> original_dict
            {1: 'z', 2: 'b', 3: 'c'}
            >>> ref_dict.inner is original_dict
            True

            ```
        """
        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
            >>> from pyochain import Dict
            >>> 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]:  # pyright: ignore[reportExplicitAny]
        """Create a `Dict` from an object `__dict__` attribute.

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

        Warning:
            This take a direct reference to the object's `__dict__`, so any modifications to the resulting `Dict` will also affect the original object's attributes, and vice versa.

        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
            >>> from pyochain import Dict
            >>> from dataclasses import dataclass
            >>> @dataclass
            ... class Person:
            ...     name: str
            ...     age: int
            >>>
            >>> person = Person("Alice", 30)
            >>> pyo_dict = Dict.from_object(person)
            >>> pyo_dict
            Dict('name': 'Alice', 'age': 30)
            >>> pyo_dict.inner is person.__dict__
            True
            >>> pyo_dict.insert("name", "Bob")
            Some('Alice')
            >>> person
            Person(name='Bob', age=30)

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

    def union(self, other: dict[K, V] | Self) -> Dict[K, V]:
        """Merge another `dict` or `Dict` with this `Dict`, returning a new one with the combined key-value pairs.

        If there are duplicate keys, the values from *other* will overwrite those in `Self`.

        This is equivalent to `|` on a standard Python `dict`.

        Args:
            other (dict[K, V] | Self): The other mapping to merge with.

        Returns:
            Dict[K, V]: A new mapping containing the merged key-value pairs.

        See Also:
            - [`Dict::union_mut`][union_mut]: Merge another mapping into `Self` in-place.

        Example:
            ```python
            >>> from pyochain import Dict
            >>> d1 = Dict({1: "a", 2: "b"})
            >>> d2 = Dict({2: "c", 3: "d"})
            >>> d3 = d1.union(d2)
            >>> d3
            Dict(1: 'a', 2: 'c', 3: 'd')
            >>> d1 is d3 or d2 is d3
            False

            ```
        """
        match other:
            case Dict():
                new = self._inner | other._inner
            case dict():
                new = self._inner | other
        return self.from_ref(new)

    def union_mut(self, other: dict[K, V] | Self) -> Self:
        """Merge another `dict` or `Dict` into `Self` in-place.

        If there are duplicate keys, the values from *other* will overwrite those in `Self`.

        This is equivalent to `|=` on a standard Python `dict`.

        Args:
            other (dict[K, V] | Self): The other mapping to merge with.

        Returns:
            Self: The modified `Dict` instance after merging.

        See Also:
            - [`Dict::union`][union]: Merge another mapping with `Self` in a new `Dict`.
            - `Dict::update` to accept any compatible `Iterable`.

        Example:
            ```python
            >>> from pyochain import Dict
            >>> d1 = Dict({1: "a", 2: "b"})
            >>> d2 = Dict({2: "c", 3: "d"})
            >>> d1.union_mut(d2)
            Dict(1: 'a', 2: 'c', 3: 'd')

            ```
        """
        match other:
            case Dict():
                self._inner |= other._inner
            case dict():
                self._inner |= other
        return self

inner property

Get the underlying dict data structure.

Useful when interoperating with functions that require a standard Python dict.

Returns:

Type Description
dict[K, V]

dict[K, V]: The underlying dictionary.

from_keys(keys, value=None) classmethod

Create a Dict from an iterable of keys, all mapped to the same value.

This is the equivalent of dict.fromkeys, but returns a Dict instance.

Parameters:

Name Type Description Default
keys Iterable[K1]

An iterable of keys to include in the mapping.

required
value V1

The value that each key will be mapped to.

None

Returns:

Type Description
Dict[K1, V1]

Dict[K1, V1]: A new PyoMapping instance containing the specified keys and value.

Example
>>> from pyochain import Dict
>>> Dict.from_keys([1, 2, 3], "a")
Dict(1: 'a', 2: 'a', 3: 'a')
>>> Dict.from_keys("abc")
Dict('a': None, 'b': None, 'c': None)
Source code in src/pyochain/_dict.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
@classmethod
def from_keys[K1, V1](cls, keys: Iterable[K1], value: V1 = None) -> Dict[K1, V1]:
    """Create a `Dict` from an iterable of keys, all mapped to the same value.

    This is the equivalent of `dict.fromkeys`, but returns a `Dict` instance.

    Args:
        keys (Iterable[K1]): An iterable of keys to include in the mapping.
        value (V1): The value that each key will be mapped to.

    Returns:
        Dict[K1, V1]: A new `PyoMapping` instance containing the specified keys and value.

    Example:
        ```python
        >>> from pyochain import Dict
        >>> Dict.from_keys([1, 2, 3], "a")
        Dict(1: 'a', 2: 'a', 3: 'a')
        >>> Dict.from_keys("abc")
        Dict('a': None, 'b': None, 'c': None)

        ```
    """
    return cls.from_ref(dict.fromkeys(keys, value))

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
>>> from pyochain import Dict
>>> Dict.from_kwargs(a=1, b=2)
Dict('a': 1, 'b': 2)
Source code in src/pyochain/_dict.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
@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
        >>> from pyochain import Dict
        >>> 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.

Warning

This take a direct reference to the object's __dict__, so any modifications to the resulting Dict will also affect the original object's attributes, and vice versa.

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
>>> from pyochain import Dict
>>> from dataclasses import dataclass
>>> @dataclass
... class Person:
...     name: str
...     age: int
>>>
>>> person = Person("Alice", 30)
>>> pyo_dict = Dict.from_object(person)
>>> pyo_dict
Dict('name': 'Alice', 'age': 30)
>>> pyo_dict.inner is person.__dict__
True
>>> pyo_dict.insert("name", "Bob")
Some('Alice')
>>> person
Person(name='Bob', age=30)
Source code in src/pyochain/_dict.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
@staticmethod
def from_object(obj: object) -> Dict[str, Any]:  # pyright: ignore[reportExplicitAny]
    """Create a `Dict` from an object `__dict__` attribute.

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

    Warning:
        This take a direct reference to the object's `__dict__`, so any modifications to the resulting `Dict` will also affect the original object's attributes, and vice versa.

    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
        >>> from pyochain import Dict
        >>> from dataclasses import dataclass
        >>> @dataclass
        ... class Person:
        ...     name: str
        ...     age: int
        >>>
        >>> person = Person("Alice", 30)
        >>> pyo_dict = Dict.from_object(person)
        >>> pyo_dict
        Dict('name': 'Alice', 'age': 30)
        >>> pyo_dict.inner is person.__dict__
        True
        >>> pyo_dict.insert("name", "Bob")
        Some('Alice')
        >>> person
        Person(name='Bob', age=30)

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

from_ref(data) staticmethod

Wrap an existing Python builtin 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 data structure, 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
>>> from pyochain import Dict
>>> original_dict = {1: "a", 2: "b", 3: "c"}
>>> ref_dict = Dict.from_ref(original_dict)
>>> ref_dict
Dict(1: 'a', 2: 'b', 3: 'c')
>>> ref_dict.insert(1, "z")
Some('a')
>>> original_dict
{1: 'z', 2: 'b', 3: 'c'}
>>> ref_dict.inner is original_dict
True
Source code in src/pyochain/_dict.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
@staticmethod
def from_ref[K1, V1](data: dict[K1, V1]) -> Dict[K1, V1]:
    """Wrap an existing Python builtin `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 data structure, 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
        >>> from pyochain import Dict
        >>> original_dict = {1: "a", 2: "b", 3: "c"}
        >>> ref_dict = Dict.from_ref(original_dict)
        >>> ref_dict
        Dict(1: 'a', 2: 'b', 3: 'c')
        >>> ref_dict.insert(1, "z")
        Some('a')
        >>> original_dict
        {1: 'z', 2: 'b', 3: 'c'}
        >>> ref_dict.inner is original_dict
        True

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

union(other)

Merge another dict or Dict with this Dict, returning a new one with the combined key-value pairs.

If there are duplicate keys, the values from other will overwrite those in Self.

This is equivalent to | on a standard Python dict.

Parameters:

Name Type Description Default
other dict[K, V] | Self

The other mapping to merge with.

required

Returns:

Type Description
Dict[K, V]

Dict[K, V]: A new mapping containing the merged key-value pairs.

See Also
Example
>>> from pyochain import Dict
>>> d1 = Dict({1: "a", 2: "b"})
>>> d2 = Dict({2: "c", 3: "d"})
>>> d3 = d1.union(d2)
>>> d3
Dict(1: 'a', 2: 'c', 3: 'd')
>>> d1 is d3 or d2 is d3
False
Source code in src/pyochain/_dict.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def union(self, other: dict[K, V] | Self) -> Dict[K, V]:
    """Merge another `dict` or `Dict` with this `Dict`, returning a new one with the combined key-value pairs.

    If there are duplicate keys, the values from *other* will overwrite those in `Self`.

    This is equivalent to `|` on a standard Python `dict`.

    Args:
        other (dict[K, V] | Self): The other mapping to merge with.

    Returns:
        Dict[K, V]: A new mapping containing the merged key-value pairs.

    See Also:
        - [`Dict::union_mut`][union_mut]: Merge another mapping into `Self` in-place.

    Example:
        ```python
        >>> from pyochain import Dict
        >>> d1 = Dict({1: "a", 2: "b"})
        >>> d2 = Dict({2: "c", 3: "d"})
        >>> d3 = d1.union(d2)
        >>> d3
        Dict(1: 'a', 2: 'c', 3: 'd')
        >>> d1 is d3 or d2 is d3
        False

        ```
    """
    match other:
        case Dict():
            new = self._inner | other._inner
        case dict():
            new = self._inner | other
    return self.from_ref(new)

union_mut(other)

Merge another dict or Dict into Self in-place.

If there are duplicate keys, the values from other will overwrite those in Self.

This is equivalent to |= on a standard Python dict.

Parameters:

Name Type Description Default
other dict[K, V] | Self

The other mapping to merge with.

required

Returns:

Name Type Description
Self Self

The modified Dict instance after merging.

See Also
  • Dict::union: Merge another mapping with Self in a new Dict.
  • Dict::update to accept any compatible Iterable.
Example
>>> from pyochain import Dict
>>> d1 = Dict({1: "a", 2: "b"})
>>> d2 = Dict({2: "c", 3: "d"})
>>> d1.union_mut(d2)
Dict(1: 'a', 2: 'c', 3: 'd')
Source code in src/pyochain/_dict.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
def union_mut(self, other: dict[K, V] | Self) -> Self:
    """Merge another `dict` or `Dict` into `Self` in-place.

    If there are duplicate keys, the values from *other* will overwrite those in `Self`.

    This is equivalent to `|=` on a standard Python `dict`.

    Args:
        other (dict[K, V] | Self): The other mapping to merge with.

    Returns:
        Self: The modified `Dict` instance after merging.

    See Also:
        - [`Dict::union`][union]: Merge another mapping with `Self` in a new `Dict`.
        - `Dict::update` to accept any compatible `Iterable`.

    Example:
        ```python
        >>> from pyochain import Dict
        >>> d1 = Dict({1: "a", 2: "b"})
        >>> d2 = Dict({2: "c", 3: "d"})
        >>> d1.union_mut(d2)
        Dict(1: 'a', 2: 'c', 3: 'd')

        ```
    """
    match other:
        case Dict():
            self._inner |= other._inner
        case dict():
            self._inner |= other
    return self