alps
alps

Reputation: 133

Indexing Python dict with string keys using Enums

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

Upvotes: 5

Views: 2982

Answers (2)

Nelala_
Nelala_

Reputation: 341

@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.

Upvotes: 7

ElmoVanKielmo
ElmoVanKielmo

Reputation: 11315

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]

Upvotes: 0

Related Questions