Construct an Enum from a Dictionary in Python


Borislav Hadzhiev

Last updated: Jun 17, 2022


Photo from Unsplash

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.
from enum import Enum my_dict = { 'SMALL': 1, 'MEDIUM': 2, 'LARGE': 3 } Sizes = Enum('Sizes', my_dict) print(Sizes) # 👉️ <enum 'Sizes'> print( # 👉️ 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.
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print( # 👉️ 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.
from enum import Enum Sizes = Enum('Sizes', 'SMALL MEDIUM LARGE') print(Sizes) # 👉️ <enum 'Sizes'> print( # 👉️ SMALL print(Sizes.SMALL.value) # 👉️ 1 print( # 👉️ 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.
from enum import Enum Sizes = Enum('Sizes', 'SMALL MEDIUM LARGE', start=10) print(Sizes) # 👉️ <enum 'Sizes'> print( # 👉️ SMALL print(Sizes.SMALL.value) # 👉️ 10 print( # 👉️ MEDIUM print(Sizes.MEDIUM.value) # 👉️ 11
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.