Stack Overflow Asked by r2_d2 on January 5, 2021
I am trying to have a map where i sometimes need to access key by value.
But if i use dictionary, i have to iterate through the dictionary to get key using value
Color = {"RED" : 3,"BLACK" : 5, "GREEN" : 10}
for color in Color:
if(Color[color] = 5):
return color
But with enum i can easily find the key by value(aliasing)
class colors(Enum):
RED = 3
BLACK = 5
GREEN = 10
colors(5).name
How is enum implemented as data structure that facilitates this? is it different from dict? and which method should i prefer for my problem?
What is best of both approaches in terms of space and time complexity?
A dictionary uses keys and values, while an enum uses attributes of an object to store/access values. you can call the items from the dictionary like so:
color["BLACK"]
using dict:
colors = {"RED" : 3,"BLACK" : 5, "GREEN" : 10}
def getKey(dct,value):
return [key for key in dct if (dct[key] == value)]
print(getKey(colors,5)[0])
in comparison to using an enum (as you already specified):
from enum import Enum
class colors(Enum):
RED = 3
BLACK = 5
GREEN = 10
print(colors(5).name)
Answered by Ironkey on January 5, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP