How To Get Enum Name By Value In Python

Get Enum name by value in Python

In this article, I will suggest how to get Enum name by value in Python using the ‘name’ attribute, the list comprehension, and the for loop. Hope you will read this article in its entirety.

Get Enum name by value in Python

Enum stands for enumeration, which is enumeration in Python. The point of Enum is that it is advantageous when representing data and representing a finite set. The Enums class generates the enumeration. An enumeration consists of names and data linked together.

To get Enum name by value in Python, you can use the following ways:

Use the ‘name’ attribute

Example:

  • Import the module named “enum”.
  • The Enums class generates enumerations. In this example, I created an enumeration named ‘FootballClubs’.
  • To get the names of Enum members, I use the ‘name’ attribute.
from enum import Enum

class FootballClubs(Enum):
	ManchesterUnited = 1
	Liverpool = 2
	ManchesterCity = 3
	NottinghamForest = 4

def getNamebyValue(val):
  # Use the "name" keyword to get the name of the enum member
  return FootballClubs(val).name

print('Enum name by 1: ', getNamebyValue(1))

Output:

Enum name by 1:  ManchesterUnited

Use list comprehension

Example:

  • Import the module named “enum “.
  • The Enums class generates enumerations. In this example, I created an enumeration named ‘FootballClubs’.
  • Use the list comprehension to get the name and value of the corresponding Enum member.
  • To get the names of Enum members, I use the ‘name’ attribute.
  • And to get the value, I use the ‘value’ attribute.
from enum import Enum

class FootballClubs(Enum):
	ManchesterUnited = 1
	Liverpool = 2
	NottinghamForest = 4    

# Value in the enum that you need to get the name
val = 2

# Use the list comprehension to get the name of the corresponding Enum member
nameOfEnum = [i.name for i in FootballClubs if i.value == val]
print(nameOfEnum)

Output:

['Liverpool']

Use the for loop

Example:

  • Import the module named “enum “.
  • The Enums class generates enumerations. In this example, I created an enumeration named ‘FootballClubs’.
  • Use the for loop to get the name and value of the corresponding Enum member.
from enum import Enum

class FootballClubs(Enum):
	ManchesterUnited = 1
	Liverpool = 2
	ManchesterCity = 3
	NottinghamForest = 4

# Value in the enum that you need to get the name
val = 3

# Use a for loop down to the members of the Enum
for club in FootballClubs:
  if club.value == val:
    print(club.name)

Output:

ManchesterCity

Summary

So that’s all for how to get Enum name by value in Python. If you have any other way or questions about this, please leave a comment, and we will try to answer them. Thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *