GDScript: Is there a difference between `for i in dict` and `for i in dict.keys`?

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

With a dictionary:

var dict = {
	"a": "hi",
	"b": "hello",
}

Using a for-each on dict seems to give the keys.

for i in dict:
	print(i)

prints:

a
b

Is there any difference between that and:

for i in dict.keys():

?

And, is there any way to iterate with a for-each over a dict in a way that gives you both keys and values? (Other than just fetching the value for the key inside the for-each)

:bust_in_silhouette: Reply From: kidscancode

The main difference is that using dict.keys() has to allocate an array before iterating. Aside from that, they’re identical.

And, is there any way to iterate with a for-each over a dict in a way that gives you both keys and values? (Other than just fetching the value for the key inside the for-each)

No, you’ll have to do the latter.

Appreciate it!

D_Steve595 | 2020-05-02 06:51