invalid index in dictionary. I'm stumped

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Robster
:warning: Old Version Published before Godot 3 was released.

Hi all,

I have JSON data in a dictionary called dict. I want to draw characters by calling the below fuction with something like drawCharacter(4).

func drawCharacter(id):
	get_node("LabelCharacterName").set_text(dict["4"]["name"])

The problem is I can’t do the above as if I try and use id in the string like below:

func drawCharacter(id):
	get_node("LabelCharacterName").set_text(dict[id]["name"])

… it doesn’t work and returns an error that it’s an invalid index.

I can ONLY get it to work if it’s wrapped in " like in the first example.

How can I make this work? I’m currently stuck. Any help very much appreciated…

if you call it as drawCharacter(4) then the id is an integer and not a string… try replacing the 4 with “4” so it will be a string and not an integer

rustyStriker | 2017-08-24 13:29

Hey there, thanks for your answer. Unfortunately the 4 in my example was just to show what might be sent. It really needs to be whatever is in id. Therefore it has to be a dynamically changing variable and not hard coded.

Robster | 2017-08-24 21:08

:bust_in_silhouette: Reply From: vctr

Use str() to convert id to string:

func drawCharacter(id):
  get_node("LabelCharacterName").set_text(dict[str(id)]["name"])

OK I’m at a loss. First of all, thank you so much. I tried that last night you see. It failed. That was the main reason I asked here. “Why can’t I convert to a string?!” I was thinking.

So then I try again this morning before replying and it … it worked. I must have been too tired and had a typo. Thanks so much. You solved the issue.

Robster | 2017-08-24 21:10

Thank you so much dude!

Darc | 2020-07-21 17:55