How to get the key of a dictionary by its number ?

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

I mean, here’s a simple dictionary:

gamevariables = new Godot.Collections.Dictionary
            {"variable_a", false},
            {"variable_b", true},
            {"variable_c", true}

If I add that:


I obtain the correct number of entries. If I add that:


It returns the correct value from “variable_a” (false).

But if I do that:


It doesn’t gives me the value of variable_a. It just crashes and returns the error “the given key was not present in the dictionary”.

So, how can I get a value from a key of that dictionary - by its number instead of by its key string?

Thank you for your time.

:bust_in_silhouette: Reply From: omggomb

You can use keys() and values() for that. Both return an array of the keys and values respectively. See here: Dictionary — Godot Engine (stable) documentation in English

So you could do: gamevariables[gamevariables.keys()[0]] or gamevariables.values()[0].

Thank you for your answer. Although, I have to admit, after countless tries, that I am absolutely clueless as of how to do convert that in C#…

I indeed knew about the existence of the “Keys” method. But it only returns an array of keys which you might think could allow you to iterate through each entry but, for a reason I can’t understand, it doesn’t.

doing this gamevariables[gamevariables.keys()[0]] is not possible in C#
and not even gamevariables.Keys[0] :confused:

Dostoi | 2022-06-01 15:01

I dug into it: You need to create an Array from Keys or Values, since they are of type ICollection which doesn’t support indexing.


var keys = new Godot.Collections.Array(gamevariables.Keys);

omggomb | 2022-06-01 15:36

That’s it! I can’t express how grateful I am for your help. Thank you omggomb.

Dostoi | 2022-06-01 16:13