Indexing Python dict with string keys using Enums

Question:

Is there a way to index a dict using an enum?

e.g. I have the following Enum and dict:

class STATUS(Enum):
    ACTIVE = "active"

d = { "active": 1 }

I’d like to add the appropriate logic to the class STATUS in order to get the following result:

d[STATUS.ACTIVE]
# returns 1

I understand that the type of STATUS.ACTIVE is not a string.. But is there a way around other than declaring the dict using STATUS.ACTIVE instead of "active"?

Also: looking for a solution other than adding a class property or .value

Asked By: alps

||

Answers:

You could use your custom dictionary class:

from collections import UserDict
from enum import Enum

class MyDict(UserDict):
    def __getitem__(self, key):
        if isinstance(key, Enum):
            key = key.value
        return super().__getitem__(key)

class STATUS(Enum):
    ACTIVE = "active"

d = MyDict({ "active": 1 })
d[STATUS.ACTIVE]
Answered By: ElmoVanKielmo

@ElmovanKielmo solution will work, however you can also achieve your desired result by making the STATUS Enum derive from str as well

from enum import Enum


class STATUS(str, Enum):
    ACTIVE = "active"


d = {"active": 1}

print(d[STATUS.ACTIVE])
# prints 1

Please keep in mind, that when inheriting from str, or any other type, the resulting enum members are also that type.

Answered By: Nelala_
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.