6

I have an Enum of days_of_the week in Python:

class days_of_the_week(str, Enum):
  monday = 'monday'
  tuesday = 'tuesday'
  wednesday = 'wednesday'
  thursday = 'thursday'
  friday = 'friday'
  saturday = 'saturday'
  sunday = 'sunday'

I want to access the value using the index.

I've tried:

days_of_the_week.value[index]
days_of_the_week[index].value
days_of_the_week.values()[index]

and so on... But everything I tried didn't returned me the value of enum (eg. days_of_the_week[1] >>> 'tuesday')

Is there a way?

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Sara Briccoli
  • 141
  • 3
  • 11

4 Answers4

7

IIUC, you want to do:

from enum import Enum

class days_of_the_week(Enum):
    monday = 0
    tuesday = 1
    wednesday = 2
    thursday = 3
    friday = 4
    saturday = 5
    sunday = 6

>>> days_of_the_week(1).name
'tuesday'
not_speshal
  • 22,093
  • 2
  • 15
  • 30
3

Those are simply string constants. They do not have an "index" and cannot be referred to that way.

However, you don't need to write that at all. Python provides it.

>>> import calendar
>>> list(calendar.day_name)
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
>>> calendar.day_name[5]
'Saturday'
>>> 
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
2

Another simple way is:

list(days_of_the_weeks)[index]

it will return the element from Enum class. If you want to get its value:

list(days_of_the_weeks)[index].value
syviad
  • 230
  • 2
  • 7
  • Is the ordering guaranteed by the Python language, or is it an implementation detail that potentially could change in the future? – Newbyte Aug 27 '23 at 14:26
0

For days of the weeks, python has inbuilt calendar module but if this is just an example, this is a way.

class days_of_the_week(str, Enum):
  monday = 'monday'
  tuesday = 'tuesday'
  wednesday = 'wednesday'
  thursday = 'thursday'
  friday = 'friday'
  saturday = 'saturday'
  sunday = 'sunday'

  @property
  def index(self):
    return list(days_of_the_week).index(self)
Rahul
  • 10,830
  • 4
  • 53
  • 88