How to make a dict from an enum?

Viewed 4143

How to make a dict from an enum?

from enum import Enum
class Shake(Enum):
    VANILLA = "vanilla"
    CHOCOLATE = "choc"
    COOKIES = "cookie"
    MINT = "mint"

dct = {}
for i in Shake:
    dct[i]=i.value

print(dct)

Output:

{<Shake.VANILLA: 'vanilla'>: 'vanilla', <Shake.CHOCOLATE: 'choc'>: 'choc', <Shake.COOKIES: 'cookie'>: 'cookie', <Shake.MINT: 'mint'>: 'mint'}

But I want the key to be VANILLA and not <Shake.VANILLA: 'vanilla'>

2 Answers

you can just use a dictionary comprehension

from enum import Enum
class Shake(Enum):
    VANILLA = "vanilla"
    CHOCOLATE = "choc"
    COOKIES = "cookie"
    MINT = "mint"

dct = {i.name: i.value for i in Shake}
print(dct)

OUTPUT

{'VANILLA': 'vanilla', 'CHOCOLATE': 'choc', 'COOKIES': 'cookie', 'MINT': 'mint'}

Edit: Don't do this, read the comments below

You can make use of map, like so

from enum import Enum
class Shake(Enum):
    VANILLA = "vanilla"
    CHOCOLATE = "choc"
    COOKIES = "cookie"
    MINT = "mint"

dct = dict(map(lambda item: (item.name, item.value), Shake))
Related