0
# Core Dictionary Operations
1
2
The main frozendict class providing an immutable dictionary with complete dict-compatible API, hashing support, and specialized methods for creating modified copies while maintaining immutability.
3
4
## Capabilities
5
6
### Construction and Initialization
7
8
Creates frozendict instances from various input types with the same constructor API as the built-in dict.
9
10
```python { .api }
11
class frozendict(dict):
12
def __init__(*args, **kwargs):
13
"""
14
Initialize frozendict with same arguments as dict.
15
16
Parameters:
17
- *args: Positional arguments (mapping, iterable of pairs, etc.)
18
- **kwargs: Keyword arguments for key-value pairs
19
"""
20
21
@classmethod
22
def fromkeys(cls, *args, **kwargs):
23
"""
24
Create frozendict from keys with default value.
25
Identical to dict.fromkeys().
26
27
Parameters:
28
- keys: Iterable of keys
29
- value: Default value for all keys (default: None)
30
31
Returns:
32
frozendict: New frozendict instance
33
"""
34
```
35
36
**Usage Example:**
37
38
```python
39
from frozendict import frozendict
40
41
# From dict
42
d1 = frozendict({'a': 1, 'b': 2})
43
44
# From key-value pairs
45
d2 = frozendict([('x', 10), ('y', 20)])
46
47
# From keyword arguments
48
d3 = frozendict(name='Alice', age=30)
49
50
# Using fromkeys
51
d4 = frozendict.fromkeys(['a', 'b', 'c'], 0) # {'a': 0, 'b': 0, 'c': 0}
52
```
53
54
### Hashing and Immutability
55
56
Provides hashing support when all values are hashable, enabling use as dictionary keys and set members.
57
58
```python { .api }
59
def __hash__(self):
60
"""
61
Return hash of frozendict if all values are hashable.
62
63
Returns:
64
int: Hash value
65
66
Raises:
67
TypeError: If any value is not hashable
68
"""
69
70
def copy(self):
71
"""
72
Return self since frozendict is immutable.
73
74
Returns:
75
frozendict: Returns self
76
"""
77
78
def __copy__(self):
79
"""
80
Support for copy.copy().
81
82
Returns:
83
frozendict: Returns self
84
"""
85
86
def __deepcopy__(self, memo):
87
"""
88
Support for copy.deepcopy().
89
90
Parameters:
91
- memo: Memoization dictionary for deepcopy
92
93
Returns:
94
frozendict: Deep copy of frozendict with deep-copied values
95
"""
96
```
97
98
**Usage Example:**
99
100
```python
101
from frozendict import frozendict
102
103
# Hashable frozendict
104
d = frozendict({'a': 1, 'b': 2})
105
my_set = {d} # Can be used in sets
106
cache = {d: "result"} # Can be used as dict keys
107
108
# Non-hashable values prevent hashing
109
d_unhashable = frozendict({'a': [1, 2, 3]})
110
# hash(d_unhashable) # Would raise TypeError
111
```
112
113
### Immutable Modifications
114
115
Methods for creating new frozendict instances with modifications while preserving immutability of the original.
116
117
```python { .api }
118
def set(self, key, val):
119
"""
120
Return new frozendict with key set to val.
121
122
Parameters:
123
- key: Key to set
124
- val: Value to set
125
126
Returns:
127
frozendict: New frozendict with modification
128
"""
129
130
def delete(self, key):
131
"""
132
Return new frozendict without key.
133
134
Parameters:
135
- key: Key to remove
136
137
Returns:
138
frozendict: New frozendict without the key
139
140
Raises:
141
KeyError: If key is not present
142
"""
143
144
def setdefault(self, key, default=None):
145
"""
146
Return new frozendict with key set to default if key is missing.
147
148
Parameters:
149
- key: Key to check and potentially set
150
- default: Value to set if key is missing (default: None)
151
152
Returns:
153
frozendict: New frozendict with key set if it was missing, or original if key existed
154
"""
155
```
156
157
**Usage Example:**
158
159
```python
160
from frozendict import frozendict
161
162
original = frozendict({'a': 1, 'b': 2})
163
164
# Create modified copies
165
updated = original.set('c', 3) # {'a': 1, 'b': 2, 'c': 3}
166
modified = original.set('a', 10) # {'a': 10, 'b': 2}
167
smaller = original.delete('b') # {'a': 1}
168
defaulted = original.setdefault('d', 4) # {'a': 1, 'b': 2, 'd': 4}
169
170
# Original remains unchanged
171
print(original) # frozendict({'a': 1, 'b': 2})
172
```
173
174
### Ordered Access
175
176
Methods for accessing items by insertion order index, maintaining compatibility with modern dict ordering.
177
178
```python { .api }
179
def key(self, index=0):
180
"""
181
Get key by insertion order index.
182
183
Parameters:
184
- index: Position index (default: 0)
185
186
Returns:
187
Key at the specified index position
188
189
Raises:
190
IndexError: If index is out of range
191
"""
192
193
def value(self, index=0):
194
"""
195
Get value by insertion order index.
196
197
Parameters:
198
- index: Position index (default: 0)
199
200
Returns:
201
Value at the specified index position
202
203
Raises:
204
IndexError: If index is out of range
205
"""
206
207
def item(self, index=0):
208
"""
209
Get (key, value) tuple by insertion order index.
210
211
Parameters:
212
- index: Position index (default: 0)
213
214
Returns:
215
tuple: (key, value) pair at the specified index position
216
217
Raises:
218
IndexError: If index is out of range
219
"""
220
```
221
222
**Usage Example:**
223
224
```python
225
from frozendict import frozendict
226
227
d = frozendict([('first', 1), ('second', 2), ('third', 3)])
228
229
# Access by index
230
print(d.key(0)) # 'first'
231
print(d.value(1)) # 2
232
print(d.item(2)) # ('third', 3)
233
234
# Negative indexing supported
235
print(d.key(-1)) # 'third'
236
print(d.value(-2)) # 2
237
```
238
239
### Union Operations
240
241
Support for union operators to merge frozendict instances.
242
243
```python { .api }
244
def __or__(self, other):
245
"""
246
Union operator |. Returns new frozendict with items from both.
247
248
Parameters:
249
- other: Mapping to merge with
250
251
Returns:
252
frozendict: New frozendict with combined items (other takes precedence)
253
"""
254
255
def __ior__(self, other):
256
"""
257
In-place union operator |=. Returns new frozendict (immutable).
258
259
Parameters:
260
- other: Mapping to merge with
261
262
Returns:
263
frozendict: New frozendict with combined items (other takes precedence)
264
"""
265
```
266
267
**Usage Example:**
268
269
```python
270
from frozendict import frozendict
271
272
d1 = frozendict({'a': 1, 'b': 2})
273
d2 = frozendict({'b': 20, 'c': 3})
274
275
# Union operations
276
merged = d1 | d2 # frozendict({'a': 1, 'b': 20, 'c': 3})
277
d1 |= d2 # d1 is now frozendict({'a': 1, 'b': 20, 'c': 3})
278
```
279
280
### Standard Dictionary Interface
281
282
All standard dictionary methods are available with read-only semantics.
283
284
```python { .api }
285
def keys(self): ...
286
def values(self): ...
287
def items(self): ...
288
def get(self, key, default=None): ...
289
def __getitem__(self, key): ...
290
def __len__(self): ...
291
def __iter__(self): ...
292
def __reversed__(self): ...
293
def __contains__(self, key): ...
294
def __repr__(self): ...
295
def __str__(self): ...
296
def __eq__(self, other): ...
297
def __ne__(self, other): ...
298
```
299
300
### Serialization Support
301
302
Built-in support for pickle and unpickle operations.
303
304
```python { .api }
305
def __reduce__(self):
306
"""
307
Support for pickle serialization.
308
309
Returns:
310
tuple: Reconstruction information for pickle
311
"""
312
```
313
314
**Usage Example:**
315
316
```python
317
import pickle
318
from frozendict import frozendict
319
320
d = frozendict({'a': 1, 'b': 2})
321
322
# Pickle and unpickle
323
pickled = pickle.dumps(d)
324
restored = pickle.loads(pickled)
325
print(restored == d) # True
326
```
327
328
## Types
329
330
```python { .api }
331
class frozendict(dict):
332
"""
333
A simple immutable dictionary that supports hashing and maintains
334
dict API compatibility while guaranteeing immutability.
335
"""
336
337
__slots__ = ("_hash",)
338
```