How to work with nested dictionaries

Godot Version

4.3.dev2

Question

I want to store all the neighboring atlas coords of each atlas coords of a tilemap in a dictionary. I want to set up the dictionary in this function:

func get_eligable_neighbors(layer: int) -> void:
	const NEIGHBORHOOD := [
		Vector2i(-1, 0),
		Vector2i(1, 0),
		Vector2i(0, -1),
		Vector2i(0, 1),
		Vector2i(-1, -1),
		Vector2i(-1, 1),
		Vector2i(1, -1),
		Vector2i(1, 1),
	]
	
	var dictionary = {}
	
	var used_rect := tilemap.get_used_rect() as Rect2i
	
	for used_cell in tilemap.get_used_cells(layer):
		var atlas_coords := tilemap.get_cell_atlas_coords(layer, used_cell)
		
		
		for direction in NEIGHBORHOOD:
			dictionary[atlas_coords] = {direction: {}}
	
	breakpoint

I’d expect the resulting dictionary to be of this sort:

var dictionary = {
	Vector2i(9, 8) = {
		Vector2i(-1, 0) = {},
		Vector2i(1, 0) = {},
		Vector2i(0, -1) = {},
		Vector2i(0, 1) = {},
		Vector2i(-1, -1) = {},
		Vector2i(-1, 1) = {},
		Vector2i(1, -1) = {},
		Vector2i(1, 1) = {},
	}
}

but instead I get this, where only the last element of the neighbor array is stored.

var dictionary = {
	Vector2i(9, 8) = {
		Vector2i(1, 1) = {},
	}
}

What am I doing wrong here? (Oh, and is there a way to declare the dictionaries like the two examples above without getting compiler errors?)

One, dictionaries are key and value pairs.

I think you mean to add the direction like this.

You were essentially adding a new value to the same key atlas_coords

ye you dont do it like that, inside dictionary to define a key and value pair here, it should be : not =

try this:

var dictionary = {
	Vector2i(9, 8) : {
		Vector2i(-1, 0) : {},
		Vector2i(1, 0) : {},
		Vector2i(0, -1) : {},
		Vector2i(0, 1) : {},
		Vector2i(-1, -1) : {"A":"hello"},
		Vector2i(-1, 1) : {},
		Vector2i(1, -1) : {},
		Vector2i(1, 1) : {},
	}
}
print(dictionary[Vector2i(9,8)][Vector2i(-1, -1)])

it should print
{ “A”: “hello” }

1 Like