I have a dictionary: { "0": {"name": Jack, "age": 23}, "1": {"name": Jim, "age": 42}, }

I want to get the name of the second dictionary. I know how to do this with a simple dictionary, but not with a dictionary inside a dictionary. All that I am trying is giving errors.

How do I get the name of the second dictionary in C#?

You can do it like this:

var person = data["1"]["name"]
6 days later

Do you have to use "var" to make it work?

I ask because it doesn't work in C#. I can't get it to work using strings inside the square brackets like data["1"]["name"]

I'll see if I can find the code. What I posted will work in GDScript, but I think in C# you have to construct a Dictionary to access nested values. I did figure it out once, but I can't find that post right now.

You can try this, not sure it will work, though:

data.1.name

Sadly, I cannot find any tutorials for C# Dictionaries in Godot, and I don't have C# setup on this computer (my other computer has C# but it died, I'm waiting for a new power supply).

@cybereality said: You can try this, not sure it will work, though:

data.1.name

Sadly, I cannot find any tutorials for C# Dictionaries in Godot, and I don't have C# setup on this computer (my other computer has C# but it died, I'm waiting for a new power supply).

The dot syntax can only be used for valid identifiers (i.e. not names that begin with numbers). You need to use the square bracket syntax for such names.

@Calinou Any ideas why the original code I posted didn't work for the OP? It's GDScript, but I thought it worked the the same in C#.

var person = data["1"]["name"]

@cybereality said: @Calinou Any ideas why the original code I posted didn't work for the OP? It's GDScript, but I thought it worked the the same in C#.

var person = data["1"]["name"]

That code is correct (well, except it's missing the semicolon). Without seeing how the dictionaries are set up or what the actual error message is, there's no way to know why it isn't working.

Here's some working C# code (not in Godot):

Dictionary<string, Dictionary<string, string>> dict = new Dictionary<string, Dictionary<string, string>>();
dict.Add("test", new Dictionary<string, string>());
dict["test"].Add("name", "david");
Console.WriteLine(dict["test"]["name"]);
9 months later