+1 vote

I'm having a weird result while iterating with dictionaries.

Say I have:

var dict = { d1={v1=0,v2=1}, d2={v1={subv=0} }

So it's a dictionary of dictionaries, and one of them has another dictionary.

I'm doing so:

for d in dict:
    return d.has("v1")

And it throws an error saying it can't find a "has" method for a String..
String? I say, so I checked it:

print(d)

And it returns "v1"... the Key, instead of the Value.
It returns the Value if I do:

print(dict[d])

Ok, so I supposed doing for d in dict: , it returns the keys.
I used to iteract with the keys by doing for key in dict.keys(): ...
I thought something was wrong, but I continued, but just after that I do an iteration ,forgetting what I have just done, with the second dictionary in dict by:

for d in dict:
    if dict[d].has("v1"):
        if typeof(dict[d].v1) == TYPE_DICTIONARY:
            for sub_d in dict[d].v1:
                print(sub_d)

And MAGIC!
As you can see, the second for is iterating in a dictionary but instead of returning the key as the previous example it returned the {subv=0} as intended.

I don't know what's going on...

in Engine by (327 points)

1 Answer

0 votes

it throws an error saying it can't find a "has" method for a String..

Yes indeed, for k in dict iterates on keys. To iterate values, you can do for v in dict.values(), but there is no way to iterate both keys and values (it was asked in a feature request I believe).

Also:

for d in dict:
    return d.has("v1")

It looks like you are expecting has() to search values (which it doesnt, it searches keys). Also it won't search recursively, so basically you won't be able to do this with a vanilla function.

I used to iteract with the keys by doing for key in dict.keys():

That also works like for k in dict, the difference is that keys() creates a new array containing the list of keys, so it might not be as efficient if you only want to iterate them.

instead of returning the key as the previous example it returned the {subv=0} as intended.

I just tried your code and that's not the case. All I get is this:

subv
by (29,088 points)
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.