Can't find a key in a dictionary but I can find it dictionary.keys(), how is this possible?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By PeterA

I am having a mind boggling problem with a dictionary

var my_dict = {…}
var i = 1

print(i in my_dict) #gives False
print(i in my_dict.keys()) #gives True

if i in my_dict.keys():
 my_dict[i] # This makes an error "Invalid get index '1' (on base: 'Dictionary')."

But it’s in the keys!!
And There is an index 1 on it I can see it in the debugger!

It’s making me question my sanity and I have no idea how to proceed to debug it

You should also show how you’re initialising the dictionary for a complete example. The following works:

var my_dict = {
  1: "foo",
  2: "bar",
}

var i = 1
print(i in my_dict) #gives False
print(i in my_dict.keys()) #gives True

print(my_dict[1]) #gives "foo"

if i in my_dict.keys():
  print(my_dict[i]) #gives "foo"

spaceyjase | 2021-11-08 18:16

:bust_in_silhouette: Reply From: kurtsev0103

I’ve just tried it in Godot 3.4-stable and it works fine.

var my_dict = {1: "kurtsev0103"}
var i = 1

print(i in my_dict) # => True
print(i in my_dict.keys()) # => True

if i in my_dict.keys():
	print(my_dict[i]) # => kurtsev0103

I would suggest double-checking your code. And keep in mind that you can use my_dict.has(i), and my_dict.get(i) or my_dict.get(i, "default_value").

P.S. If you showed what your “my_dict” looks like, it would be clearer and you would be helped more accurately.

As it turned out, the var was a float, and not an integer.

print(1.0 in [1])# This is true
print(1.0 in {1:0})# This is false

PeterA | 2021-11-08 19:02

:bust_in_silhouette: Reply From: timothybrentwood

One is probably a string and the other is probably an integer. Test that theory with this:

var i = 1
var expected_value_for_key = 1 # replace with whatever it is
for key in my_dict:
	if my_dict.get(key) == expected_value_for_key:
		printt(typeof(i), typeof(key))

Found the problem with typeof

One was an integer, and one was a float.

print(1.0 in [1])# This is true
print(1.0 in {1:0})# This is false

This was very confusing because I knew it wasn’t a string because I could do math with it. The dictionary is strict with the typing and the list isn’t. That was the source of the confusion.

Should it be raised as an issue, or is this intended behaviour?

PeterA | 2021-11-08 18:58

Should it be raised as an issue, or is this intended behaviour?

It’s not an issue since I believe keys for a dictionary can be anything that inherits from Variant by design. I have issues with the way floats print in the console, which was the cause of your debugging issue here, but I don’t think changing how floats print will pick up much traction.

timothybrentwood | 2021-11-08 19:30