Skip to content

Python frozendict

  • by

The concept of a frozendict does not exist in the standard Python library. However, you can create an immutable dictionary-like object by using the types.MappingProxyType class from the types module. This class creates a read-only view of a dictionary.

import types

original_dict = {'key1': 'value1', 'key2': 'value2'}
frozen_dict = types.MappingProxyType(original_dict)

# Trying to modify the frozen_dict will raise a TypeError
# frozen_dict['key1'] = 'new_value'  # Raises TypeError

# You can still access the items in the frozen_dict
print(frozen_dict['key1'])  # Output: value1

# If the original dictionary changes, the frozen_dict will reflect the changes
original_dict['key1'] = 'modified_value'
print(frozen_dict['key1'])  # Output: modified_value

By using types.MappingProxyType, you create an immutable view of the original dictionary. Any attempt to modify the frozen_dict will raise a TypeError. However, keep in mind that the objects inside the dictionary can still be mutable, and changes made to them will be reflected in the frozen_dict.

Python frozendict example

There are third-party libraries, such as frozendict, that provide an implementation of an immutable dictionary.

The frozendict library allows you to create immutable dictionaries in Python. Immutable dictionaries are useful when you want to create a dictionary that cannot be modified once it is created. Here’s an example of how to use the frozendict library:

First, you need to install the library using pip:

pip install frozendict

Then, you can create a frozendict object:

from frozendict import frozendict

fd = frozendict({'a': 1, 'b': 2, 'c': 3})
print(fd)  # {'a': 1, 'b': 2, 'c': 3}

Output:

Python frozendict

The frozendict object behaves like a regular dictionary, allowing you to access its elements:

value = fd['a']
print(value)  # 1

However, you cannot modify a frozendict object once it is created:

fd['d'] = 4  # Raises TypeError

This is because frozendict objects are immutable, meaning their contents cannot be changed after creation.

Please note that frozendict is not a built-in part of the Python standard library. It is a separate library that you need to install if you wish to use it.

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.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading