|
| Home |
|---|
A Python immutable dictionary is a dictionary-like data structure whose contents cannot be changed after it has been created. Unlike a normal Python dictionary, which is mutable, an immutable or read-only dictionary prevents code from adding, updating, or deleting dictionary entries through the read-only interface.
Python dictionaries are mutable by default. This means that you can add new key-value pairs, change existing values, and remove items after creating a dictionary. However, there are situations where dictionary data should be protected from accidental modification.
Python does not provide a built-in immutable dict type in the same way that it provides the immutable tuple type. However, Python's types.MappingProxyType can be used to create a read-only dictionary view.
This tutorial explains how to create an immutable or read-only dictionary in Python, how MappingProxyType works, how it differs from a normal dictionary, and when immutable dictionary-like structures are useful.
No, Python dictionaries are mutable. A normal Python dictionary can be modified after it is created. You can add new items, change existing values, and remove items.
For example, the following dictionary is mutable:
student = {
"name": "Alice",
"age": 21
}
student["age"] = 22
print(student)
{'name': 'Alice', 'age': 22}
The value associated with the "age" key changed from 21 to 22. This happens because a standard Python dictionary is mutable.
An immutable dictionary is a dictionary-like structure whose key-value mappings cannot be changed through the object after it has been created.
For example, you may have configuration data that should be available throughout an application but should not be modified accidentally:
settings = {
"language": "English",
"max_attempts": 3,
"debug": False
}
If these values represent fixed application settings, allowing every part of a program to modify them may create unexpected behavior. A read-only dictionary can provide a safer interface for accessing such data.
Python does not have a built-in immutable_dict or frozendict type in the standard library equivalent to tuple for lists.
However, Python provides MappingProxyType in the types module. It creates a read-only mapping proxy around an existing dictionary.
This is one of the most useful standard-library approaches when you need a dictionary that cannot be modified through the exposed object.
To create a read-only dictionary view, import MappingProxyType from the types module and pass a dictionary to it.
from types import MappingProxyType
data = {
"name": "Alice",
"age": 21
}
immutable_data = MappingProxyType(data)
print(immutable_data)
{'name': 'Alice', 'age': 21}
The resulting immutable_data object can be used to read the dictionary values, but it does not allow modifications through the proxy.
A MappingProxyType object can be accessed much like a normal dictionary. You can retrieve values using keys.
from types import MappingProxyType
data = {
"name": "Alice",
"age": 21,
"course": "Python"
}
immutable_data = MappingProxyType(data)
print(immutable_data["name"])
print(immutable_data["course"])
Alice
Python
Read operations such as looking up a value are allowed. The restriction applies to operations that attempt to modify the mapping.
If you try to assign a new value through a MappingProxyType object, Python raises a TypeError.
from types import MappingProxyType
data = {
"name": "Alice",
"age": 21
}
immutable_data = MappingProxyType(data)
immutable_data["age"] = 25
TypeError: 'mappingproxy' object does not support item assignment
The error occurs because the mapping proxy does not support item assignment.
You also cannot add a new key-value pair through the read-only mapping.
from types import MappingProxyType
data = {
"name": "Alice",
"age": 21
}
immutable_data = MappingProxyType(data)
immutable_data["city"] = "London"
TypeError: 'mappingproxy' object does not support item assignment
The mapping proxy prevents the new key from being added.
Deletion is also not allowed through a MappingProxyType object.
from types import MappingProxyType
data = {
"name": "Alice",
"age": 21
}
immutable_data = MappingProxyType(data)
del immutable_data["age"]
TypeError: 'mappingproxy' object does not support item deletion
Therefore, a mapping proxy prevents the caller from adding, changing, or deleting dictionary entries through the proxy.
One of the most important things to understand about Python's MappingProxyType is that it creates a read-only view of the original dictionary. It does not create a separate independent copy.
This means that changes made to the original dictionary are visible through the mapping proxy.
from types import MappingProxyType
data = {
"a": 1,
"b": 2
}
proxy = MappingProxyType(data)
data["c"] = 3
print(proxy)
{'a': 1, 'b': 2, 'c': 3}
The proxy now contains the new "c" entry because the original dictionary was changed.
This is an important distinction: the proxy itself is read-only, but the original dictionary is still mutable.
The term "immutable dictionary" is often used informally when discussing MappingProxyType, but technically it is more accurate to describe it as a read-only mapping view.
Consider the following relationship:
This distinction becomes particularly important when designing applications where data must remain completely fixed.
If you want other parts of a program to have read-only access, one practical approach is to keep the original dictionary private and expose only the mapping proxy.
from types import MappingProxyType
_config = {
"host": "localhost",
"port": 8080,
"debug": False
}
CONFIG = MappingProxyType(_config)
print(CONFIG["host"])
print(CONFIG["port"])
localhost
8080
Code using CONFIG cannot directly modify the mapping. The original _config dictionary remains available inside the module, allowing the module itself to control whether and when changes are made.
Configuration values are a common use case for read-only mappings. For example, an application may define fixed settings that should be available throughout the program.
from types import MappingProxyType
_app_config = {
"app_name": "Student Portal",
"max_login_attempts": 5,
"session_timeout": 30,
"maintenance_mode": False
}
APP_CONFIG = MappingProxyType(_app_config)
print(APP_CONFIG["app_name"])
print(APP_CONFIG["session_timeout"])
Student Portal
30
Other functions can read these settings without being able to accidentally replace values through APP_CONFIG.
A read-only mapping can also be useful for lookup tables that should not normally change while a program is running.
from types import MappingProxyType
_country_codes = {
"Pakistan": "PK",
"United Kingdom": "GB",
"United States": "US",
"Canada": "CA"
}
COUNTRY_CODES = MappingProxyType(_country_codes)
print(COUNTRY_CODES["Pakistan"])
print(COUNTRY_CODES["United Kingdom"])
PK
GB
Using a read-only mapping communicates the intention that the lookup table is not supposed to be modified by normal application code.
It is important to understand that MappingProxyType protects the dictionary mapping itself. It does not automatically make nested mutable objects immutable.
For example, a dictionary may contain a list as one of its values:
from types import MappingProxyType
data = {
"name": "Alice",
"subjects": ["Python", "SQL"]
}
proxy = MappingProxyType(data)
proxy["subjects"].append("Statistics")
print(proxy)
{'name': 'Alice', 'subjects': ['Python', 'SQL', 'Statistics']}
The dictionary entry itself cannot be replaced through the proxy, but the list stored as the value is still mutable.
This is an example of shallow read-only protection. If deeply immutable data is required, the nested objects must also use immutable representations.
Another approach is to represent fixed key-value data using a tuple containing pairs.
data = (
("name", "Alice"),
("age", 21)
)
print(data)
(('name', 'Alice'), ('age', 21))
Tuples are immutable, so the tuple structure cannot be changed after creation.
However, tuples do not provide the same convenient dictionary interface. For example, you cannot directly use data["name"] because tuples use integer indexes.
Therefore, tuples can be useful for fixed collections of pairs, but they are not a direct replacement for a read-only dictionary.
| Feature | Dictionary | MappingProxyType | Tuple of Pairs |
|---|---|---|---|
| Key-value lookup | Yes | Yes | No direct key lookup |
| Normally mutable | Yes | No through proxy | No |
| Can add items | Yes | No | No |
| Can delete items | Yes | No | No |
| Reflects original dictionary changes | Not applicable | Yes | No |
Python provides frozenset as an immutable version of a set, but there is no equivalent built-in frozendict type in the standard library.
A frozenset is designed for collections of unique values, whereas a dictionary stores key-value relationships.
numbers = frozenset([1, 2, 3, 4])
print(numbers)
frozenset({1, 2, 3, 4})
For dictionary-like read-only data, MappingProxyType is the standard-library option to consider.
A normal dictionary cannot be used as a dictionary key because dictionaries are mutable and therefore unhashable.
data = {
"name": "Alice",
"age": 21
}
# This raises TypeError
lookup = {
data: "student"
}
TypeError: unhashable type: 'dict'
Making a dictionary read-only with MappingProxyType does not turn it into a hashable dictionary key. If you need an immutable, hashable representation of key-value data, a different representation may be required, such as a carefully constructed tuple of immutable key-value pairs.
A read-only dictionary is useful when data should be accessed by many parts of an application but should not normally be modified by those parts of the program.
Configuration values such as application names, limits, feature settings, and default options can be exposed through a read-only mapping.
Read-only dictionaries are useful for lookup information such as country codes, status codes, category mappings, and predefined application values.
When several functions need access to the same mapping, exposing a read-only view can reduce the possibility of accidental modification.
A library may want to return mapping data that callers can inspect without allowing them to modify the library's internal dictionary through the returned object.
Read-only mappings can make program intent clearer. If a value is intended to be constant, exposing it through a read-only interface helps prevent accidental assignments.
Suppose a function maintains a collection of application settings. Instead of returning the internal dictionary directly, it can return a mapping proxy.
from types import MappingProxyType
_settings = {
"theme": "light",
"language": "English",
"items_per_page": 20
}
def get_settings():
return MappingProxyType(_settings)
settings = get_settings()
print(settings["theme"])
print(settings["language"])
light
English
The caller can read the settings without receiving a normal mutable dictionary interface.
Although read-only mappings are useful, they do not automatically solve every problem associated with mutable data.
MappingProxyType is a read-only view rather than an independent immutable copy.immutable_dict typeMappingProxyType creates a copy of the original dictionaryThe key difference between a normal mutable dictionary and a read-only dictionary is whether the mapping can be modified through the object being used.
| Operation | Normal Dictionary | MappingProxyType |
|---|---|---|
| Read a value | Yes | Yes |
| Change a value | Yes | No |
| Add a key | Yes | No |
| Delete a key | Yes | No |
| Iterate over keys | Yes | Yes |
Use keys(), values(), and items() |
Yes | Yes |
The simplest standard-library method is to use MappingProxyType.
from types import MappingProxyType
data = {
"name": "Alice",
"age": 21
}
read_only_data = MappingProxyType(data)
print(read_only_data["name"])
Alice
The basic pattern is therefore:
from types import MappingProxyType
original = {...}
read_only = MappingProxyType(original)
The resulting object provides read-only mapping access to the original dictionary.
For most standard-library Python applications, MappingProxyType is a good choice when the goal is to expose a dictionary as read-only.
However, it is important to choose the data structure based on the actual requirement:
No. A standard Python dictionary is mutable. Its keys and values can be added, changed, or removed after the dictionary is created.
For a read-only dictionary interface, use MappingProxyType from Python's types module. It creates a read-only view of an existing dictionary.
MappingProxyType is a read-only mapping view provided by Python's types module. It allows dictionary-style access while preventing modifications through the proxy.
No. You cannot add, update, or delete items through the mapping proxy. Attempting to do so raises a TypeError.
No. MappingProxyType creates a read-only view of the original dictionary. Changes made directly to the original dictionary can be visible through the proxy.
No. It protects the dictionary mapping itself, but nested mutable objects such as lists or sets can still be modified unless they are separately converted to immutable structures.
A MappingProxyType object is not a replacement for a hashable immutable dictionary and should not be treated as one. If key-value data needs to be used as a dictionary key, an appropriate hashable representation must be created.
Python's standard library does not provide a built-in frozendict type. MappingProxyType provides a read-only mapping view, while third-party packages can provide other immutable dictionary implementations when stronger immutability is required.
A normal Python dictionary is mutable, meaning that its contents can be changed after creation. Python does not provide a built-in immutable dictionary type equivalent to tuple or frozenset.
For a read-only dictionary interface, Python provides MappingProxyType in the types module. It prevents assignments, additions, and deletions through the proxy while still allowing normal dictionary-style reading and iteration.
The most important point to remember is that MappingProxyType is a read-only view rather than a completely independent immutable copy. Changes to the original dictionary can still be reflected in the proxy, and nested mutable values can remain mutable.
Understanding Python mutable and immutable data structures is important when working with configuration data, shared application state, APIs, libraries, and larger Python projects.
Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.
Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.
Home Tutorial Online Live Trainings Contact Us © 2026 All rights reserved by www.PythonTutor.net