Immutable Dictionary

4.3.1 · active · verified Sun Apr 05

immutabledict is a Python library providing an immutable wrapper around dictionaries. It functions as a drop-in replacement for standard dictionaries where immutability is desired, implementing the complete mapping interface. Forked from `frozendict`, `immutabledict` offers an MIT-licensed alternative to the LGPL-3.0 licensed original. It also includes `ImmutableOrderedDict` for order-preserving immutable mappings. The library is actively maintained with frequent minor and patch releases.

Warnings

Install

Imports

Quickstart

Demonstrates how to create an immutabledict and shows that direct modification attempts will result in a TypeError. It also illustrates how to create a new immutabledict based on an existing one with updates.

from immutabledict import immutabledict

# Create an immutable dictionary
my_item = immutabledict({"a": "value", "b": "other_value"})

print(f"Value for 'a': {my_item['a']}")

# Attempting to modify an immutabledict will raise a TypeError
try:
    my_item["c"] = "new_value"
except TypeError as e:
    print(f"Attempted modification failed: {e}")

# You can create a new immutabledict with changes using dictionary union operator (PEP 584)
new_item = my_item | {"c": "another_value"}
print(f"New item (original unchanged): {new_item}")
print(f"Original item: {my_item}")

view raw JSON →