How to make immutable dictionaries in Python #PyTip01

Problem


>>> person = {“id” : 735616, “first_name”: “John”, “last_name”:”Doe”}
>>> person[“id”]
735616
>>> person[“first_name”] + ‘ ‘ + person[“last_name”]
‘John Doe’
>>> person[“id”] = 000000
>>> person[“id”]
0

Solution


>>> from types import MappingProxyType
>>> im_person = MappingProxyType({“id”:736533, “first_name”:”John”, “last_name”:”Doe”})
>>> im_person[“id”]
736533
>>> im_person[“id”] = 87
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
TypeError: ‘mappingproxy’ object does not support item assignment

Caveat

>>> im_person = MappingProxyType(person)
>>> im_person
mappingproxy({‘id’: 0, ‘first_name’: ‘John’, ‘last_name’: ‘Doe’})
>>> person
{‘id’: 0, ‘first_name’: ‘John’, ‘last_name’: ‘Doe’}
>>> person[“id”] = 00
>>> im_person
mappingproxy({‘id’: 0, ‘first_name’: ‘John’, ‘last_name’: ‘Doe’})
>>>

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vivek

Vivek

I am a leaner. Python Programmer. Creating content around Python and Web Development