How to append to array in a dict?

Godot Version

4.2.2

Question

I want to have a dict containing an array, ie:

GM_commands = {gamecode:[command1, command2...]}

But when I try to append a command to the dict:

var GM_commands = {}

func _ready():
    var gamecode = "ABC"
    var command = "start_game"

    GM_commands[gamecode]=[] #so that the dict {"ABC":[]} exists
    GM_commands[gamecode].append(command)

The last line gives me the error “Invalid get index 'append' (on base: 'array')” which I don’t understand.

What am I doing wrong please? Thanks

You should try this:

var GM_commands = {}

func _ready():
	var gamecode = "ABC"
	var command = "start_game"

	GM_commands.gamecode=[] #so that the dict {"ABC":[]} exists
	GM_commands.gamecode.append(command)
	print(GM_commands)

In Godot, you can also access dictionary keys that way

This works perfectly fine for me in 4.2.2.stable
Mind sharing the full script?

1 Like

I restarted the server, and now it works without giving me an error message, so I have no idea what that error was about, sorry. Thanks for checking it out for me.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.