Is this supposed to work like this with dictionaries?

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

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…

:bust_in_silhouette: Reply From: Zylann

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