Enums as dictionary keys - why isn't this working?

Godot Version

4.3

Question

If I have an enum defined like this:
enum Test { FOO, BAR }

… and a dictionary:
var dict = { Test.FOO : "Foo", Test.BAR : "Bar"}

I can access the values directly without problems:
print(dict.get(Test.FOO, "-")) -> prints "Foo"

BUT, when I iterate the enum in a for loop, the keys aren’t found:

for t in Test:
    print(t)
    print(dict.get(t, "-"))

output:

FOO
-
BAR
-

What is going on here, and how can I fix this?

TL;DR: Use Test.values() instead of Test.

When you iterate over a enum, the prop u get is the key of it as u showed in the 1st and 3rd lines of your output.

But, when u used your enum as a key to the dictionary, it doesn’t uses the enum key, but it’s value. Is the same as write:

var dict = { 0: "Foo", 1: "Bar"}

This way, in the iteration the t is FOO/BAR because it is the key, but the dictionary uses it’s value.

Just use Test.values() to iterate over the enum values so u can have what you want.

4 Likes

The key of enumeration is a number,
If you don’t believe, print it out and take a look.

enum Test { FOO, BAR }
print(Test.FOO)
print(Test.BAR)

Makes perfect sense, thank you!

That would get the value of the enumerated type. Under the hood enums are a lot like Dictionaries, including how dictionaries operate in a for loop, by getting the keys.

Try this test out and take a look

enum Test { FOO, BAR }
print(type_string(typeof(Test.FOO))) # int

for i in Test: # same as `for i in Test.keys()`
    print(type_string(typeof(i))) # string; string

for i in Test.values():
    print(type_string(typeof(i))) # int; int

More from the docs:

If you pass a name to the enum, it will put all the keys inside a constant Dictionary of that name. This means all constant methods of a dictionary can also be used with a named enum.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.