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'>
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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With