Construct an Enum from a Dictionary in Python

avatar

Borislav Hadzhiev

Fri Jun 17 20222 min read

Construct an Enum from a Dictionary in Python #

Use the functional API to construct an enum from a dictionary, e.g. Sizes = Enum('Sizes', my_dict). The first argument we pass to the Enum class is the name of the enumeration, and the second - the source of the enumeration member names and values.

main.py
from enum import Enum my_dict = { 'SMALL': 1, 'MEDIUM': 2, 'LARGE': 3 } Sizes = Enum('Sizes', my_dict) print(Sizes) # 👉️ <enum 'Sizes'> print(Sizes.SMALL.name) # 👉️ SMALL print(Sizes.SMALL.value) # 👉️ 1

We used the functional API for enum creation.

The Enum class is callable and takes the name of the enumeration as the first argument and the source of enumeration names as the second.

The second argument can be:

  • a mapping (e.g. a dictionary)
  • a sequence of tuples with 2 elements (key and value)
  • whitespace-separated string of names
  • a sequence of names

The Sizes enum we created using the functional API is equivalent to the following enum.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes.SMALL.name) # 👉️ SMALL print(Sizes.SMALL.value) # 👉️ 1

If we pass a dictionary to the functional API, we assign the values of the dictionary as the values for the corresponding keys.

If we use a whitespace-separated string of names or a sequence of names, the enum values get auto-assigned increasing integers starting with 1.

main.py
from enum import Enum Sizes = Enum('Sizes', 'SMALL MEDIUM LARGE') print(Sizes) # 👉️ <enum 'Sizes'> print(Sizes.SMALL.name) # 👉️ SMALL print(Sizes.SMALL.value) # 👉️ 1 print(Sizes.MEDIUM.name) # 👉️ MEDIUM print(Sizes.MEDIUM.value) # 👉️ 2

The code sample creates the same enum as in the previous examples.

You can optionally pass a start argument to the functional API if you need to specify a different starting value.

main.py
from enum import Enum Sizes = Enum('Sizes', 'SMALL MEDIUM LARGE', start=10) print(Sizes) # 👉️ <enum 'Sizes'> print(Sizes.SMALL.name) # 👉️ SMALL print(Sizes.SMALL.value) # 👉️ 10 print(Sizes.MEDIUM.name) # 👉️ MEDIUM print(Sizes.MEDIUM.value) # 👉️ 11
Use the search field on my Home Page to filter through my more than 1,000 articles.