Skip to content

Python constant dictionary

  • by

There is no constant in Python, so a truly constant dictionary is not possible. However, you can create a constant by using a dictionary that is read-only (i.e., can’t be modified after initialization) and contains key-value pairs that represent the constant values.

Python constant dictionary example

Simple example code makes the dictionary read-only by setting __readonly___ attribute

CON_DICT = {
    "a": 10,
    "b": 20,
    "c": 90
}


# Make the dictionary read-only by setting __readonly__ attribute
class ReadOnlyDict(dict):
    __readonly__ = True

    def __setitem__(self, key, value):
        if self.__readonly__:
            raise TypeError("Can't modify read-only dictionary")
        return super().__setitem__(key, value)


CON_DICT['c'] = 30

RES_DICT = ReadOnlyDict(CON_DICT)

print(RES_DICT)
RES_DICT['c'] = 90

Output:

Python constant dictionary

What are Python’s best practices for dictionary dict key constants?

Answer: First Use uppercase letters and underscores to name your constants. Then Use frozenset and Enum class to define constants.

from enum import Enum


class Keys(Enum):
NAME = "name"
AGE = "age"
EMAIL = "email"


my_dict = {
Keys.NAME: "John",
Keys.AGE: 25,
Keys.EMAIL: "[email protected]"
}

print(my_dict)
my_dict['Keys.NAME'] = "FN"

Do comment if you have any doubts or suggestions on this Python constant 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