Python Tutoring Online
 Home

Python Immutable Dictionary:## Create Read-Only Dictionaries

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.

Need Help Learning Python?

Understanding mutable and immutable data structures is an important part of learning Python programming. If you are working with dictionaries, functions, data structures, or Python projects, practical examples can make these concepts much easier to understand.

An online Python tutor can help you understand Python dictionaries, mutable and immutable objects, data structures, and object-oriented programming through practical examples.

Get Python Tutoring Help

Are Python Dictionaries Immutable?

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:

Python
student = {
    "name": "Alice",
    "age": 21
}

student["age"] = 22

print(student)

Output


{'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.

What Is an Immutable Dictionary in Python?

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:

Python
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.

Does Python Have a Built-In Immutable Dictionary?

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.

Creating an Immutable Dictionary Using MappingProxyType

To create a read-only dictionary view, import MappingProxyType from the types module and pass a dictionary to it.

Python
from types import MappingProxyType

data = {
    "name": "Alice",
    "age": 21
}

immutable_data = MappingProxyType(data)

print(immutable_data)

Output


{'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.

Reading Values From an Immutable Dictionary

A MappingProxyType object can be accessed much like a normal dictionary. You can retrieve values using keys.

Python
from types import MappingProxyType

data = {
    "name": "Alice",
    "age": 21,
    "course": "Python"
}

immutable_data = MappingProxyType(data)

print(immutable_data["name"])
print(immutable_data["course"])

Output


Alice
Python

Read operations such as looking up a value are allowed. The restriction applies to operations that attempt to modify the mapping.

Trying to Change an Immutable Dictionary

If you try to assign a new value through a MappingProxyType object, Python raises a TypeError.

Python
from types import MappingProxyType

data = {
    "name": "Alice",
    "age": 21
}

immutable_data = MappingProxyType(data)

immutable_data["age"] = 25

Output


TypeError: 'mappingproxy' object does not support item assignment

The error occurs because the mapping proxy does not support item assignment.

Adding a New Item to an Immutable Dictionary

You also cannot add a new key-value pair through the read-only mapping.

Python
from types import MappingProxyType

data = {
    "name": "Alice",
    "age": 21
}

immutable_data = MappingProxyType(data)

immutable_data["city"] = "London"

Output


TypeError: 'mappingproxy' object does not support item assignment

The mapping proxy prevents the new key from being added.

Deleting an Item From an Immutable Dictionary

Deletion is also not allowed through a MappingProxyType object.

Python
from types import MappingProxyType

data = {
    "name": "Alice",
    "age": 21
}

immutable_data = MappingProxyType(data)

del immutable_data["age"]

Output


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.

MappingProxyType Is a Read-Only View, Not a Copy

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.

Python
from types import MappingProxyType

data = {
    "a": 1,
    "b": 2
}

proxy = MappingProxyType(data)

data["c"] = 3

print(proxy)

Output


{'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.

MappingProxyType vs a Truly Immutable Dictionary

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.

Making the Original Dictionary Inaccessible

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.

Python
from types import MappingProxyType

_config = {
    "host": "localhost",
    "port": 8080,
    "debug": False
}

CONFIG = MappingProxyType(_config)

print(CONFIG["host"])
print(CONFIG["port"])

Output


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.

Immutable Dictionary Example for Application Configuration

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.

Python
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"])

Output


Student Portal
30

Other functions can read these settings without being able to accidentally replace values through APP_CONFIG.

Immutable Dictionary for Constant Lookup Data

A read-only mapping can also be useful for lookup tables that should not normally change while a program is running.

Python
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"])

Output


PK
GB

Using a read-only mapping communicates the intention that the lookup table is not supposed to be modified by normal application code.

Immutable Dictionary and Nested Data

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:

Python
from types import MappingProxyType

data = {
    "name": "Alice",
    "subjects": ["Python", "SQL"]
}

proxy = MappingProxyType(data)

proxy["subjects"].append("Statistics")

print(proxy)

Output


{'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.

Using Tuples for Immutable Key-Value Data

Another approach is to represent fixed key-value data using a tuple containing pairs.

Python
data = (
    ("name", "Alice"),
    ("age", 21)
)

print(data)

Output


(('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.

Immutable Dictionary vs Tuple

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

Immutable Dictionary vs Frozen Set

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.

Python
numbers = frozenset([1, 2, 3, 4])

print(numbers)

Output


frozenset({1, 2, 3, 4})

For dictionary-like read-only data, MappingProxyType is the standard-library option to consider.

Can an Immutable Dictionary Be Used as a Dictionary Key?

A normal dictionary cannot be used as a dictionary key because dictionaries are mutable and therefore unhashable.

Python
data = {
    "name": "Alice",
    "age": 21
}

# This raises TypeError
lookup = {
    data: "student"
}

Output


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.

When Should You Use an Immutable Dictionary?

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.

1. Application Configuration

Configuration values such as application names, limits, feature settings, and default options can be exposed through a read-only mapping.

2. Constant Lookup Tables

Read-only dictionaries are useful for lookup information such as country codes, status codes, category mappings, and predefined application values.

3. Shared Application Data

When several functions need access to the same mapping, exposing a read-only view can reduce the possibility of accidental modification.

4. API and Library Design

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.

5. Preventing Accidental Changes

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.

Example: Returning Read-Only Data From a Function

Suppose a function maintains a collection of application settings. Instead of returning the internal dictionary directly, it can return a mapping proxy.

Python
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"])

Output


light
English

The caller can read the settings without receiving a normal mutable dictionary interface.

Benefits of Read-Only Dictionaries

Limitations of Immutable Dictionaries in Python

Although read-only mappings are useful, they do not automatically solve every problem associated with mutable data.

Common Beginner Mistakes With Immutable Dictionaries

Mutable Dictionary vs Immutable Dictionary

The 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

How to Make a Read-Only Dictionary in Python

The simplest standard-library method is to use MappingProxyType.

Python
from types import MappingProxyType

data = {
    "name": "Alice",
    "age": 21
}

read_only_data = MappingProxyType(data)

print(read_only_data["name"])

Output


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.

Python Immutable Dictionary: Best Approach

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:

Frequently Asked Questions About Python Immutable Dictionaries

Is a Python dictionary immutable?

No. A standard Python dictionary is mutable. Its keys and values can be added, changed, or removed after the dictionary is created.

How do I make a dictionary immutable in Python?

For a read-only dictionary interface, use MappingProxyType from Python's types module. It creates a read-only view of an existing dictionary.

What is MappingProxyType in Python?

MappingProxyType is a read-only mapping view provided by Python's types module. It allows dictionary-style access while preventing modifications through the proxy.

Can I change a MappingProxyType dictionary?

No. You cannot add, update, or delete items through the mapping proxy. Attempting to do so raises a TypeError.

Does MappingProxyType copy the dictionary?

No. MappingProxyType creates a read-only view of the original dictionary. Changes made directly to the original dictionary can be visible through the proxy.

Is MappingProxyType deeply immutable?

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.

Can an immutable dictionary be used as a dictionary key?

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.

Is there a frozendict in Python?

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.

Summary

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.

Related Python Dictionary Tutorials




Stuck Learning Python?

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.

    Get Python Tutoring

PythonTutor.net

Home    Tutorial     Online Live Trainings    Contact Us           © 2026 All rights reserved by www.PythonTutor.net