0

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?

r2_d2
  • 203
  • 3
  • 14

1 Answers1

1

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)
Ironkey
  • 2,568
  • 1
  • 8
  • 30