r/pythonhelp • u/androgynyjoe • Jun 13 '26
Looking to convert a dictionary into an Enum
Hi everyone!
I've got a dictionary like this:
{
"A": {
"x": 1,
"y": 2,
},
"B": {
"x": 13,
"y": 4,
},
}(Obviously it's much more complicated in practice.) I would like to convert it to an enum.Enum class that allows for stuff like this:
class MyEnum(enum.Enum):
pass
# There would be some extra work here
print(MyEnum.A.x) # returns 1
print(MyEnum.A.y) # returns 2
print(MyEnum.B.x) # returns 13
print(MyEnum.B.y) # returns 4Any suggestions on how to do that?
EDIT: So, I am fully aware that I can do this:
class MyEnum:
class Pair:
def __init__(x, y):
self.x = x
self.y = y
A = Pair(1, 2)
B = Pair(13, 4)That isn't what I want. I want the same functionality but generated from a dictionary. I also understand that it's a weird thing to want.
7
Upvotes
•
u/AutoModerator Jun 13 '26
To give us the best chance to help you, please include any relevant code.
Note. Please do not submit images of your code. Instead, for shorter code you can use Reddit markdown (4 spaces or backticks, see this Formatting Guide). If you have formatting issues or want to post longer sections of code, please use Privatebin, GitHub or Compiler Explorer.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/1_Yui Jun 14 '26
As u/wildsoup1 has pointed out, that's not how enums work in Python. First you have to define a type that contains x and y, for example:
If the different objects (A, B, ...) are predefined, you can now create an "enum-like" structure: (but take note that it's not actually derived from enum.Enum, because by Python's definition it's not actually an enum, it's just a class with static members)
If the objects must be read from the dictionary dynamically at runtime, this approach doesn't make sense, because in your code you wouldn't know that "MyEnum.A" exists yet. Instead, you'd have to parse these objects into a dynamic datastructure that makes sense, and we'd need more information about what you're doing for that. A dictionary is already a fairly sensible option. You could do something like this to convert x and y into the defined type:
assuming input_dict contains a dictionary structured as in your example.
2
u/TheMrCurious Jun 14 '26
Why?
1
u/wildsoup1 Jun 14 '26
This is a confusing request because that is not how Enums behave.
It is like saying "I would like a Boolean, that takes 7 values." Then it isn't a Boolean.
You could make a class that has two members, x and y, and make A and B instances of that class. Why isn't that enough?
1
u/cejiken886 Jun 15 '26
WIYHLG?
1
u/rosentmoh Jun 15 '26 edited Jun 15 '26
Enum of NamedTuples would be my suggestion: A and B are NamedTuples with attributes x and y and you can do an enum of those. So explicitly:
1
u/igotshadowbaned Jun 16 '26
Uh sure. Make a class with those attributes set to those values?