Saturday 11 September 2021

Python: Use enum members as dictionary keys

Enumeration members are immutable, so they can be used in dictionaries and sets.

 

Example

quotes = {}
quotes[Day.MONDAY] = 'Journey started'
quotes[Day.SATURDAY] = 'Happy week end'

 

enumsInDictKey.py

from enum import Enum

class Day(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

quotes = {}
quotes[Day.MONDAY] = 'Journey started'
quotes[Day.SATURDAY] = 'Happy week end'

print(quotes)

 

Output

{<Day.MONDAY: 1>: 'Journey started', <Day.SATURDAY: 6>: 'Happy week end'}

 

 

 


Previous                                                    Next                                                    Home

No comments:

Post a Comment