Basically, Python dictionary data structures mean you can modify the contents of a dictionary by adding, deleting, or changing its key-value pairs. Using types.MappingProxyType you can create an immutable dict in Python.
from types import MappingProxyType
power_levels = MappingProxyType(
{
"Kevin": 9001,
"Benny": 8000,
}
)
The MappingProxyType
function takes a dictionary as an argument and returns a new object that behaves like a read-only view of the original dictionary.
Python immutable dict example
Simple example code immutable dictionary using the MappingProxyType
function:
import types
original_dict = {'name': 'John', 'age': 25}
immutable_dict = types.MappingProxyType(original_dict)
print(immutable_dict)
# modify the immutable dictionary
immutable_dict['name'] = 'Bob' # error
Output:
Difference between MappingProxyType and PEP 416 frozendict
MappingProxyType
is a read-only proxy for mapping (e.g. dict) objects and frozendict
is an immutable dict.
The MappingProxyType
is just a simple proxy (i.e. interface) to access the real object (the real map, which in our example is dict).
the suggested frozendict
the object is just as the set is to frozenset. a read-only (immutable) object which can only be changed upon creation.
So why do we need MappingProxyType
? example use case is where you want to pass a dictionary to another function but without it being able to change your dictionary, it acts as a read-only proxy, (quoting python docs):
Do comment if you have any doubts or suggestions on this Python dictionary topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.