0 votes

I'm tripping... but I don't understand why .has() isn't detecting a Dictionary key.

Here's my code:

print(dict.keys())
# ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"]

print(typeof(dict.keys()[10]))
# 4
print(typeof(str(10)))
# 4
print(typeof("10"))
# 4

# https://docs.godotengine.org/en/stable/classes/[email protected]
# TYPE_STRING = 4

THIS WORKS:

if dict.has(dict.keys()[10]):
    # YES FOUND!

NONE OF THESE WORK:

if dict.has(str(10)):
if dict.has("10"):
if dict.has('10'):
if dict.has(10):
    # All 4 evaluate to boolean FALSE

If I do this

var x = dict['10']
# I get this error: Invalid get index '10' (on base: 'Dictionary')

What could possibly be going wrong?

There should be a string index "10" but it doesn't work unless I reference it with .keys()[10]

in Engine by (183 points)
edited by

That seems to work for me

How are you declaring your keys?
I notice in my output my keys (which are strings) don't have quotes around them...

Crazy question, do your keys include quotes INSIDE the string?

var dict = {}
for i in range(0,20):
    var j = str(i)
    dict[j] = i
dict["test string"] = 100

print(dict)
print(dict.keys())
print(typeof(dict.keys()[10]))
print(typeof(str(10)))
print(typeof("10"))

print(dict.has(str(10)))    # Should be True if key is a string
print(dict.has("10"))       # Should be True if key is a string
print(dict.has('10'))       # Should be True if key is a string
print(dict.has(10))         # Should be False if key is a string

Returns this
{0:0, 1:1, 10:10, 11:11, 12:12, 13:13, 14:14, 15:15, 16:16, 17:17, 18:18, 19:19, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, test string:100}
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, test string]
4
4
4
True
True
True
False

DUDE! That's it!

I had to force quotes in an array to use within a Dictionary for JSON reasons (long story) and forgot that's how it was stored.

Once I changed it to the below it worked:
if dict.has('"'+str(10)+'"'):

Thanks Andy!

BTW, if you want to add your quotes comment as an answer I can accept it so others in the future are more likely in the future to view.

Super!
I will add a quick Answer.
Thanks

1 Answer

+2 votes
Best answer

Do your Dictionary keys include quotes INSIDE the string?

It looks like your keys are strings, but probably do not match your .has() method calls because they include extra quotes within the actual string.

by (541 points)
selected by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.