[Python] How to Create Immutable Dictionaries & Sets in Python?
![[Python] How to Create Immutable Dictionaries & Sets in Python?](https://cdn.hashnode.com/res/hashnode/image/upload/v1734267990871/88a30076-9e88-45a7-b68d-9a2a4fe32747.png)
What are Immutable Dictionaries & Sets?
Before reading this article, you should have an understanding of mutable and immutable types in python. You can look at my article that explains them pretty easy: [CS fundamentals] Mutable vs. Immutable.
Dictotionaries and sets are mutable as we can change values. For example:
d = {'key1': 'value1'}
print(d) # {'key1': 'value1'}
d['key2'] = 'value2'
d.setdefault('key3', 'value3')
print(d) # {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
s = {'Apple', 'Orange', "Apple", "Orange", 'Kiwi'}
print(s) # {'Kiwi', 'Orange', 'Apple'}
s.add('Melon')
print(s) # {'Melon', 'Kiwi', 'Orange', 'Apple'}
As you may see, the values of d and s can be changed, which means they are mutable.
Immutable Dictionaries and Sets
Creating Immutable Dictionary:
from types import MappingProxyType
d = {'key1': 'value1'}
# Read-only
d_frozen = MappingProxyType(d)
print(d_frozen) # {'key1': 'value1'}
d_frozen['key2'] = 'value2' # error
You can make your dictionary as immutable by using
MappingProxyTypefunction in types module.
You are making your dictionary as read-only, so that your co-workers cannot edit the sensitive data stored in your immutable dictionary.
If you try to assign a new key-value pair, it will print an error.
Traceback (most recent call last):
File "your_file", line 14, in <module>
d_frozen['key2'] = 'value2'
TypeError: 'mappingproxy' object does not support item assignment
Creating Immutable Set:
s = frozenset(['Apple', 'Orange', "Apple", "Orange", 'Kiwi'])
s.add('Melon') # error
It’s very simple. You can use frozenset() to make it immutable. Just like a dictionary, immutable set is also read-only, so that the data are not changed by someone.
If you try to modify it, it will print an error:
Traceback (most recent call last):
File "your_file", line 29, in <module>
s6.add('Melon')
AttributeError: 'frozenset' object has no attribute 'add'
![[CS fundamentals] Greedy - Dijkstra, Kruskal and Prim's Algorithm](https://cdn.hashnode.com/uploads/covers/644c253f17f6efe1e02ade41/f62b4d41-5a31-4cd3-9d44-a7004f4624b9.jpg)
![[CS fundamentals] Linked List Creation & Insertion explained in C.](https://cdn.hashnode.com/uploads/covers/644c253f17f6efe1e02ade41/6a74e5c0-44ca-4110-9ee7-e8e67767a9dc.png)
![[CS Fundamentals] Pointers in C](https://cdn.hashnode.com/uploads/covers/644c253f17f6efe1e02ade41/6f81f5a6-d87c-4382-883f-fa4d0a8b5968.png)
![[SQL] Writing Efficient SQL Queries](https://cdn.hashnode.com/res/hashnode/image/upload/v1751292603168/b0b43c7d-8e08-47b2-a64c-b600e3511831.jpeg)
![[CS Fundamentals] Binary Search](https://cdn.hashnode.com/res/hashnode/image/upload/v1747041878054/c8d8adb9-097d-484b-9562-f43e4bce9a46.png)