How to add / append to a Dictionary of Dictionaries

Godot Version

v4.4.1 stable

Question

Super noob question, but what’s the best way to add to a Dictionary in GDScript? I want something like the “append” function of Arrays. I have a Dictionary of Dictionaries and I want to add to it in other parts of the script, here’s my code:

This is the initial setup of “test_data” the parent Dictionary:

# Save battle data
func save_battle_data() -> void:
	test_data = {
		0: {
			"FileName": Data.generate_file_name(),
			"Rounds": round_limit,
		},
		1: {
			"ChampionID": 0,
			"Name": "Alena",
			"Damage": 150
		}
	}

Here’s where I’m trying to add to the Dictionary using the “get_or_add“ function:

		BATTLE_STATE.POST_BATTLING_PHASE:
			turn_timer.stop()
			end_battle()
			save_battle_data()
			test_data.get_or_add({
				2: {
					"ChampionID": 1,
					"Name": "Annabel",
					"Damage": 100
				}
			})
			Data.save_training_dummy_battle(test_data)

But the “get_or_add” function comes out like this:

I couldn’t find much help on Google, does anyone know a good way to do this?

dict.set(key, value)

or

dict[key] = value
1 Like

Do you want to merge the dictionaries? You could use the .merge function if so.

But it looks like you should assign the new key directly instead

test_data["2"] = {
	"ChampionID": 1,
	"Name": "Annabel",
	"Damage": 100
}
1 Like

Omg I knew it was going to be something stupidly easy lol.

Thank you, that’s exactly what I wanted.

Cheers.

Yeah I thought about that, but I knew there would be an easier way “.set“ is what I was looking for, but thank you for that too.

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