Skip to content

c108.collections

Bidirectional mapping utilities providing a generic BiDirectionalMap with forward and reverse lookups.

BiDirectionalMap

Bases: Mapping[K, V], Generic[K, V]

A bidirectional mapping that maintains one-to-one correspondence between keys and values.

Implements the standardMapping protocol for forward lookups (key -> value) while providing efficient reverse lookups (value -> key). Both keys and values must be hashable and unique.

Examples:

>>> bimap = BiDirectionalMap({'a': 1, 'b': 2})
>>> bimap['a']  # Forward lookup
1
>>> bimap.get_key(1)  # Reverse lookup
'a'
>>> 'a' in bimap  # Key membership
True
>>> bimap.has_value(1)  # Value membership
True
>>> bimap.to_dict()  # Extract as standarddict
{'a': 1, 'b': 2}
>>> bimap.reversed()  # Get reversed mapping
BiDirectionalMap({1: 'a', 2: 'b'})

Forward direction (key -> value): - Implements full Mapping protocol: getitem, iter, len, keys(), values(), items(), get() - Membership testing (x in bimap) applies to keys only, like dict

Reverse direction (value -> key): - get_key(value): lookup key by value (raises KeyError if not found) - has_value(value): test if value exists

Conversion and views
  • to_dict(): extract as standarddict (key -> value)
  • reversed(): create new BiDirectionalMap with swapped keys/values
Mutation operations maintain bidirectional consistency
  • add(key, value): add new mapping, both must be unique
  • set(key, value): set/update mapping for key, value must be unique
  • pop(key, default=None): remove and return value for key
  • delete(key): remove mapping for key
  • update(mapping): bulk update with uniqueness validation
  • clear(): remove all mappings

Raises:

Type Description
ValueError

When attempting to add duplicate keys or values

KeyError

When accessing non-existent keys or values

TypeError

When keys or values are not hashable

Source code in c108/collections.py
 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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
class BiDirectionalMap(Mapping[K, V], Generic[K, V]):
    """
    A bidirectional mapping that maintains one-to-one correspondence between keys and values.

    Implements the standardMapping protocol for forward lookups (key -> value) while providing
    efficient reverse lookups (value -> key). Both keys and values must be hashable and unique.

    Examples:
        >>> bimap = BiDirectionalMap({'a': 1, 'b': 2})
        >>> bimap['a']  # Forward lookup
        1
        >>> bimap.get_key(1)  # Reverse lookup
        'a'
        >>> 'a' in bimap  # Key membership
        True
        >>> bimap.has_value(1)  # Value membership
        True
        >>> bimap.to_dict()  # Extract as standarddict
        {'a': 1, 'b': 2}
        >>> bimap.reversed()  # Get reversed mapping
        BiDirectionalMap({1: 'a', 2: 'b'})

    Forward direction (key -> value):
        - Implements full Mapping protocol: __getitem__, __iter__, __len__, keys(), values(), items(), get()
        - Membership testing (x in bimap) applies to keys only, like dict

    Reverse direction (value -> key):
        - get_key(value): lookup key by value (raises KeyError if not found)
        - has_value(value): test if value exists

    Conversion and views:
        - to_dict(): extract as standarddict (key -> value)
        - reversed(): create new BiDirectionalMap with swapped keys/values

    Mutation operations maintain bidirectional consistency:
        - add(key, value): add new mapping, both must be unique
        - set(key, value): set/update mapping for key, value must be unique
        - pop(key, default=None): remove and return value for key
        - delete(key): remove mapping for key
        - update(mapping): bulk update with uniqueness validation
        - clear(): remove all mappings

    Raises:
        ValueError: When attempting to add duplicate keys or values
        KeyError: When accessing non-existent keys or values
        TypeError: When keys or values are not hashable
    """

    def __init__(self, initial: Mapping[K, V] | Iterable[tuple[K, V]] | None = None) -> None:
        """
        Initialize bidirectional map.

        Args:
            initial: Optional initial data as mapping or iterable of (key, value) pairs

        Raises:
            ValueError: If initial data contains duplicate keys or values
            TypeError: If keys or values are not hashable
        """
        self._forward_map: dict[K, V] = {}
        self._backward_map: dict[V, K] = {}
        if initial:
            self._init_from_data(initial)

    def _init_from_data(self, data: Mapping[K, V] | Iterable[tuple[K, V]]) -> None:
        """
        Initialize from data with strict duplicate validation.

        If the input `data` is another `BiDirectionalMap` instance, its internal maps are
        directly copied for efficiency, bypassing re-validation. Otherwise, it iterates
        through the data, validating uniqueness of keys and values.

        Args:
            data: Mapping or iterable of (key, value) pairs

        Raises:
            ValueError: If duplicate keys or values are found
        """
        if isinstance(data, BiDirectionalMap):
            # If initializing from another BiDirectionalMap, we can directly copy
            # its internal maps as uniqueness is already guaranteed.
            self._forward_map.update(data._forward_map)
            self._backward_map.update(data._backward_map)
        else:
            iterable = data.items() if isinstance(data, abc.Mapping) else data
            seen_keys: set[K] = set()
            seen_values: set[V] = set()

            for k, v in iterable:
                if k in seen_keys:
                    raise ValueError(f"Key already exists: {k!r}")
                if v in seen_values:
                    raise ValueError(f"Value already exists: {v!r}")
                seen_keys.add(k)
                seen_values.add(v)
                self._forward_map[k] = v
                self._backward_map[v] = k

    # ----- Mapping required methods -----

    def __getitem__(self, key: K) -> V:
        """Get value for key. Raises KeyError if key not found."""
        return self._forward_map[key]

    def __iter__(self) -> Iterator[K]:
        """Iterate over keys."""
        return iter(self._forward_map)

    def __len__(self) -> int:
        """Return number of key-value pairs."""
        return len(self._forward_map)

    def __contains__(self, key: object) -> bool:
        """Test if key exists (standardMapping behavior)."""
        return key in self._forward_map

    # ----- Mapping helpers (typed views) -----

    def keys(self) -> KeysView[K]:
        """Return view of keys."""
        return self._forward_map.keys()

    def values(self) -> ValuesView[V]:
        """Return view of values."""
        return self._forward_map.values()

    def items(self) -> ItemsView[K, V]:
        """Return view of (key, value) pairs."""
        return self._forward_map.items()

    def get(self, key: object, default: V | None = None) -> V | None:
        """Get value for key, returning default if key not found."""
        return self._forward_map.get(key, default)

    # ----- Bidirectional operations -----

    def get_value(self, key: object) -> V:
        """
        Get value for key (alias for __getitem__).

        Args:
            key: The key to look up

        Returns:
            The value associated with the key

        Raises:
            KeyError: If key not found
        """
        return self._forward_map[key]

    def get_key(self, value: object) -> K:
        """
        Get key for value (reverse lookup).

        Args:
            value: The value to look up

        Returns:
            The key associated with the value

        Raises:
            KeyError: If value not found
        """
        return self._backward_map[value]

    def has_value(self, value: object) -> bool:
        """
        Test if value exists in the mapping.

        Args:
            value: The value to test for

        Returns:
            True if value exists, False otherwise
        """
        return value in self._backward_map

    # ----- Conversion and views -----

    def to_dict(self) -> dict[K, V]:
        """
        Extract as standarddictionary (key -> value mapping).

        Returns a shallow copy of the forward mapping as a standarddict.
        Modifications to the returned dict do not affect this BiDirectionalMap.

        Returns:
            A new dict containing all key-value pairs

        Examples:
            >>> bimap = BiDirectionalMap({'a': 1, 'b': 2})
            >>> d = bimap.to_dict()
            >>> d
            {'a': 1, 'b': 2}
            >>> d['c'] = 3  # Does not affect bimap
        """
        return dict(self._forward_map)

    def reversed(self) -> "BiDirectionalMap[V, K]":
        """
        Create new BiDirectionalMap with keys and values swapped.

        Returns a new BiDirectionalMap where the original values become keys
        and the original keys become values. The original mapping is unchanged.

        Returns:
            A new BiDirectionalMap with swapped key-value pairs

        Examples:
            >>> bimap = BiDirectionalMap({'a': 1, 'b': 2})
            >>> rev = bimap.reversed()
            >>> rev.to_dict()
            {1: 'a', 2: 'b'}
            >>> rev[1]
            'a'
        """
        return BiDirectionalMap(self._backward_map)

    # ----- Mutations (keep both maps consistent) -----

    def add(self, key: K, value: V) -> None:
        """
        Add a new key-value pair. Both key and value must be unique.

        Args:
            key: The key to add
            value: The value to add

        Raises:
            ValueError: If key already exists or value already exists
            TypeError: If key or value is not hashable
        """
        if key in self._forward_map:
            raise ValueError(
                f"Key already exists: {fmt_any(key)} maps to {fmt_any(self._forward_map[key])})"
            )
        if value in self._backward_map:
            raise ValueError(
                f"Value already exists: {fmt_any(value)} mapped from {fmt_any(self._backward_map[value])})"
            )
        self._forward_map[key] = value
        self._backward_map[value] = key

    def set(self, key: K, value: V) -> None:
        """
        Set or update mapping for key. Value must be unique across all mappings.

        If key exists, its old value is released. The new value must not be
        used by any other key.

        Args:
            key: The key to set
            value: The value to associate with key

        Raises:
            ValueError: If value already exists (mapped from a different key)
            TypeError: If key or value is not hashable
        """
        if key in self._forward_map:
            old_value = self._forward_map[key]
            if old_value == value:
                return  # no-op
            if value in self._backward_map and self._backward_map[value] != key:
                raise ValueError(
                    f"Value already exists: {fmt_any(value)} mapped from {fmt_any(self._backward_map[value])}"
                )
            del self._backward_map[old_value]
        else:
            if value in self._backward_map:
                raise ValueError(
                    f"Value already exists: {fmt_any(value)} mapped from {fmt_any(self._backward_map[value])}"
                )

        self._forward_map[key] = value
        self._backward_map[value] = key

    @overload
    def pop(self, key: object) -> V: ...

    @overload
    def pop(self, key: object, default: V) -> V: ...

    def pop(self, key: object, default: V = MISSING) -> V:
        """
        Remove mapping for key and return its value.

        Args:
            key: The key to remove
            default: Value to return if key not found

        Returns:
            The value that was associated with key, or default if key not found

        Raises:
            KeyError: If key not found and no default provided
        """
        if key not in self._forward_map:
            if default is not MISSING:
                return default  # type: ignore[return-value]
            raise KeyError(key)
        value = self._forward_map.pop(key)
        del self._backward_map[value]
        return value

    def delete(self, key: object) -> None:
        """
        Remove mapping for key.

        Args:
            key: The key to remove

        Raises:
            KeyError: If key not found
        """
        value = self._forward_map.pop(key)  # type: ignore[arg-type]
        del self._backward_map[value]

    def clear(self) -> None:
        """Remove all mappings."""
        self._forward_map.clear()
        self._backward_map.clear()

    def update(self, other: Mapping[K, V] | Iterable[tuple[K, V]]) -> None:
        """
        Update with key-value pairs from another mapping or iterable.

        Uses set() semantics: existing keys are updated, new keys are added.
        All values must satisfy uniqueness constraints.

        Args:
            other: Mapping or iterable of (key, value) pairs

        Raises:
            ValueError: If any value would violate uniqueness constraints
            TypeError: If any key or value is not hashable
        """
        iterable = other.items() if isinstance(other, abc.Mapping) else other
        for k, v in iterable:
            self.set(k, v)

    # ----- Equality and representation -----

    def __repr__(self) -> str:
        """Return string representation."""
        return f"BiDirectionalMap({self._forward_map!r})"

    def __eq__(self, other: Any) -> bool:
        """Test equality with another mapping based on key-value pairs."""
        if isinstance(other, abc.Mapping):
            return dict(self._forward_map.items()) == dict(other.items())
        return NotImplemented

__contains__(key)

Test if key exists (standardMapping behavior).

Source code in c108/collections.py
135
136
137
def __contains__(self, key: object) -> bool:
    """Test if key exists (standardMapping behavior)."""
    return key in self._forward_map

__eq__(other)

Test equality with another mapping based on key-value pairs.

Source code in c108/collections.py
370
371
372
373
374
def __eq__(self, other: Any) -> bool:
    """Test equality with another mapping based on key-value pairs."""
    if isinstance(other, abc.Mapping):
        return dict(self._forward_map.items()) == dict(other.items())
    return NotImplemented

__getitem__(key)

Get value for key. Raises KeyError if key not found.

Source code in c108/collections.py
123
124
125
def __getitem__(self, key: K) -> V:
    """Get value for key. Raises KeyError if key not found."""
    return self._forward_map[key]

__init__(initial=None)

Initialize bidirectional map.

Parameters:

Name Type Description Default
initial Mapping[K, V] | Iterable[tuple[K, V]] | None

Optional initial data as mapping or iterable of (key, value) pairs

None

Raises:

Type Description
ValueError

If initial data contains duplicate keys or values

TypeError

If keys or values are not hashable

Source code in c108/collections.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def __init__(self, initial: Mapping[K, V] | Iterable[tuple[K, V]] | None = None) -> None:
    """
    Initialize bidirectional map.

    Args:
        initial: Optional initial data as mapping or iterable of (key, value) pairs

    Raises:
        ValueError: If initial data contains duplicate keys or values
        TypeError: If keys or values are not hashable
    """
    self._forward_map: dict[K, V] = {}
    self._backward_map: dict[V, K] = {}
    if initial:
        self._init_from_data(initial)

__iter__()

Iterate over keys.

Source code in c108/collections.py
127
128
129
def __iter__(self) -> Iterator[K]:
    """Iterate over keys."""
    return iter(self._forward_map)

__len__()

Return number of key-value pairs.

Source code in c108/collections.py
131
132
133
def __len__(self) -> int:
    """Return number of key-value pairs."""
    return len(self._forward_map)

__repr__()

Return string representation.

Source code in c108/collections.py
366
367
368
def __repr__(self) -> str:
    """Return string representation."""
    return f"BiDirectionalMap({self._forward_map!r})"

add(key, value)

Add a new key-value pair. Both key and value must be unique.

Parameters:

Name Type Description Default
key K

The key to add

required
value V

The value to add

required

Raises:

Type Description
ValueError

If key already exists or value already exists

TypeError

If key or value is not hashable

Source code in c108/collections.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def add(self, key: K, value: V) -> None:
    """
    Add a new key-value pair. Both key and value must be unique.

    Args:
        key: The key to add
        value: The value to add

    Raises:
        ValueError: If key already exists or value already exists
        TypeError: If key or value is not hashable
    """
    if key in self._forward_map:
        raise ValueError(
            f"Key already exists: {fmt_any(key)} maps to {fmt_any(self._forward_map[key])})"
        )
    if value in self._backward_map:
        raise ValueError(
            f"Value already exists: {fmt_any(value)} mapped from {fmt_any(self._backward_map[value])})"
        )
    self._forward_map[key] = value
    self._backward_map[value] = key

clear()

Remove all mappings.

Source code in c108/collections.py
341
342
343
344
def clear(self) -> None:
    """Remove all mappings."""
    self._forward_map.clear()
    self._backward_map.clear()

delete(key)

Remove mapping for key.

Parameters:

Name Type Description Default
key object

The key to remove

required

Raises:

Type Description
KeyError

If key not found

Source code in c108/collections.py
328
329
330
331
332
333
334
335
336
337
338
339
def delete(self, key: object) -> None:
    """
    Remove mapping for key.

    Args:
        key: The key to remove

    Raises:
        KeyError: If key not found
    """
    value = self._forward_map.pop(key)  # type: ignore[arg-type]
    del self._backward_map[value]

get(key, default=None)

Get value for key, returning default if key not found.

Source code in c108/collections.py
153
154
155
def get(self, key: object, default: V | None = None) -> V | None:
    """Get value for key, returning default if key not found."""
    return self._forward_map.get(key, default)

get_key(value)

Get key for value (reverse lookup).

Parameters:

Name Type Description Default
value object

The value to look up

required

Returns:

Type Description
K

The key associated with the value

Raises:

Type Description
KeyError

If value not found

Source code in c108/collections.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
def get_key(self, value: object) -> K:
    """
    Get key for value (reverse lookup).

    Args:
        value: The value to look up

    Returns:
        The key associated with the value

    Raises:
        KeyError: If value not found
    """
    return self._backward_map[value]

get_value(key)

Get value for key (alias for getitem).

Parameters:

Name Type Description Default
key object

The key to look up

required

Returns:

Type Description
V

The value associated with the key

Raises:

Type Description
KeyError

If key not found

Source code in c108/collections.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
def get_value(self, key: object) -> V:
    """
    Get value for key (alias for __getitem__).

    Args:
        key: The key to look up

    Returns:
        The value associated with the key

    Raises:
        KeyError: If key not found
    """
    return self._forward_map[key]

has_value(value)

Test if value exists in the mapping.

Parameters:

Name Type Description Default
value object

The value to test for

required

Returns:

Type Description
bool

True if value exists, False otherwise

Source code in c108/collections.py
189
190
191
192
193
194
195
196
197
198
199
def has_value(self, value: object) -> bool:
    """
    Test if value exists in the mapping.

    Args:
        value: The value to test for

    Returns:
        True if value exists, False otherwise
    """
    return value in self._backward_map

items()

Return view of (key, value) pairs.

Source code in c108/collections.py
149
150
151
def items(self) -> ItemsView[K, V]:
    """Return view of (key, value) pairs."""
    return self._forward_map.items()

keys()

Return view of keys.

Source code in c108/collections.py
141
142
143
def keys(self) -> KeysView[K]:
    """Return view of keys."""
    return self._forward_map.keys()

pop(key, default=MISSING)

pop(key: object) -> V
pop(key: object, default: V) -> V

Remove mapping for key and return its value.

Parameters:

Name Type Description Default
key object

The key to remove

required
default V

Value to return if key not found

MISSING

Returns:

Type Description
V

The value that was associated with key, or default if key not found

Raises:

Type Description
KeyError

If key not found and no default provided

Source code in c108/collections.py
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def pop(self, key: object, default: V = MISSING) -> V:
    """
    Remove mapping for key and return its value.

    Args:
        key: The key to remove
        default: Value to return if key not found

    Returns:
        The value that was associated with key, or default if key not found

    Raises:
        KeyError: If key not found and no default provided
    """
    if key not in self._forward_map:
        if default is not MISSING:
            return default  # type: ignore[return-value]
        raise KeyError(key)
    value = self._forward_map.pop(key)
    del self._backward_map[value]
    return value

reversed()

Create new BiDirectionalMap with keys and values swapped.

Returns a new BiDirectionalMap where the original values become keys and the original keys become values. The original mapping is unchanged.

Returns:

Type Description
BiDirectionalMap[V, K]

A new BiDirectionalMap with swapped key-value pairs

Examples:

>>> bimap = BiDirectionalMap({'a': 1, 'b': 2})
>>> rev = bimap.reversed()
>>> rev.to_dict()
{1: 'a', 2: 'b'}
>>> rev[1]
'a'
Source code in c108/collections.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
def reversed(self) -> "BiDirectionalMap[V, K]":
    """
    Create new BiDirectionalMap with keys and values swapped.

    Returns a new BiDirectionalMap where the original values become keys
    and the original keys become values. The original mapping is unchanged.

    Returns:
        A new BiDirectionalMap with swapped key-value pairs

    Examples:
        >>> bimap = BiDirectionalMap({'a': 1, 'b': 2})
        >>> rev = bimap.reversed()
        >>> rev.to_dict()
        {1: 'a', 2: 'b'}
        >>> rev[1]
        'a'
    """
    return BiDirectionalMap(self._backward_map)

set(key, value)

Set or update mapping for key. Value must be unique across all mappings.

If key exists, its old value is released. The new value must not be used by any other key.

Parameters:

Name Type Description Default
key K

The key to set

required
value V

The value to associate with key

required

Raises:

Type Description
ValueError

If value already exists (mapped from a different key)

TypeError

If key or value is not hashable

Source code in c108/collections.py
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
def set(self, key: K, value: V) -> None:
    """
    Set or update mapping for key. Value must be unique across all mappings.

    If key exists, its old value is released. The new value must not be
    used by any other key.

    Args:
        key: The key to set
        value: The value to associate with key

    Raises:
        ValueError: If value already exists (mapped from a different key)
        TypeError: If key or value is not hashable
    """
    if key in self._forward_map:
        old_value = self._forward_map[key]
        if old_value == value:
            return  # no-op
        if value in self._backward_map and self._backward_map[value] != key:
            raise ValueError(
                f"Value already exists: {fmt_any(value)} mapped from {fmt_any(self._backward_map[value])}"
            )
        del self._backward_map[old_value]
    else:
        if value in self._backward_map:
            raise ValueError(
                f"Value already exists: {fmt_any(value)} mapped from {fmt_any(self._backward_map[value])}"
            )

    self._forward_map[key] = value
    self._backward_map[value] = key

to_dict()

Extract as standarddictionary (key -> value mapping).

Returns a shallow copy of the forward mapping as a standarddict. Modifications to the returned dict do not affect this BiDirectionalMap.

Returns:

Type Description
dict[K, V]

A new dict containing all key-value pairs

Examples:

>>> bimap = BiDirectionalMap({'a': 1, 'b': 2})
>>> d = bimap.to_dict()
>>> d
{'a': 1, 'b': 2}
>>> d['c'] = 3  # Does not affect bimap
Source code in c108/collections.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def to_dict(self) -> dict[K, V]:
    """
    Extract as standarddictionary (key -> value mapping).

    Returns a shallow copy of the forward mapping as a standarddict.
    Modifications to the returned dict do not affect this BiDirectionalMap.

    Returns:
        A new dict containing all key-value pairs

    Examples:
        >>> bimap = BiDirectionalMap({'a': 1, 'b': 2})
        >>> d = bimap.to_dict()
        >>> d
        {'a': 1, 'b': 2}
        >>> d['c'] = 3  # Does not affect bimap
    """
    return dict(self._forward_map)

update(other)

Update with key-value pairs from another mapping or iterable.

Uses set() semantics: existing keys are updated, new keys are added. All values must satisfy uniqueness constraints.

Parameters:

Name Type Description Default
other Mapping[K, V] | Iterable[tuple[K, V]]

Mapping or iterable of (key, value) pairs

required

Raises:

Type Description
ValueError

If any value would violate uniqueness constraints

TypeError

If any key or value is not hashable

Source code in c108/collections.py
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
def update(self, other: Mapping[K, V] | Iterable[tuple[K, V]]) -> None:
    """
    Update with key-value pairs from another mapping or iterable.

    Uses set() semantics: existing keys are updated, new keys are added.
    All values must satisfy uniqueness constraints.

    Args:
        other: Mapping or iterable of (key, value) pairs

    Raises:
        ValueError: If any value would violate uniqueness constraints
        TypeError: If any key or value is not hashable
    """
    iterable = other.items() if isinstance(other, abc.Mapping) else other
    for k, v in iterable:
        self.set(k, v)

values()

Return view of values.

Source code in c108/collections.py
145
146
147
def values(self) -> ValuesView[V]:
    """Return view of values."""
    return self._forward_map.values()