![]() |
Attention | Topic was automatically imported from the old Question2Answer platform. |
![]() |
Asked By | eod |
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/class_@globalscope.html
# 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]
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
AndyCampbell | 2020-12-09 12:50
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.
eod | 2020-12-09 16:56
Super!
I will add a quick Answer.
Thanks
AndyCampbell | 2020-12-09 17:39