KeyError: 0 while trying to set value in 3 dimensional list.

So basically I’m trying to expand upon TaeZ’s sample here. I’ve created a CubeManager class that will be adding/removing the appropriate vertices and faces from the main mesh when I need it to.

Here’s what I’ve got so far:

from meshgenerator import MeshGenerator

class CubeManager():
	def __init__(self):
		self.cubes = {}
		self.mesh = MeshGenerator('blocks')

	def addCube(self, x, y, z, blockID):
		self.cubes[x][y][z] = blockID

		if x-1 not in self.cubes or self.cubes[x-1][y][z] == 0:
			self.mesh.makeLeftFace(x, y, z, id)
		if x+1 not in self.cubes or self.cubes[x+1][y][z] == 0:
			self.mesh.makeRightFace(x, y, z, id)
		if y-1 not in self.cubes or self.cubes[x][y-1][z] == 0:
			self.mesh.makeBackFace(x, y, z, id)
		if y+1 not in self.cubes or self.cubes[x][y+1][z] == 0:
			self.mesh.makeFrontFace(x, y, z, id)
		if z-1 not in self.cubes or self.cubes[x][y][z-1] == 0:
			self.mesh.makeBottomFace(x, y, z, id)
		if z+1 not in self.cubes or self.cubes[x][y][z+1] == 0:
			self.mesh.makeTopFace(x, y, z, id)

	def delCube(self, x, y, z):
		self.cubes[x][y][z] = 0
		#Code to remove faces

	def getGeomNode(self):
		return mesh.getGeomNode()

When I run this, I get KeyError: 0 at the line:

self.cubes[x][y][z] = blockID

I have not the slightest clue what this means or how to go about fixing this, so I’m hoping somebody with more experience can help me out. Thanks to anyone who does help!

The important distinction here is that you do not have a 3-dimensional list, but a 3-dimensional dictionary.
KeyError means the dictionary does not have the key you are passing to it.
For this code to work you would have to first initialize self.cubes with a structure of nested dictionaries.
That is what this part of the code in the sample is doing:

for x in range(0, 25):
    cubes[x] = {}
    for y in range(0, 25):
        cubes[x][y] = {}
        for z in range(0, 25):
            cubes[x][y][z] = randint(0, 2)

Ah, well that’s definitely good to know! I had just assumed he was using a list. Obviously, I don’t have much experience in Python as of yet, I have a couple years of experience in C# however.
So now what I’m wondering is whether there’s a performance difference between using a dictionary and using a list to hold this data.

A list is faster, but probably the reason why a dictionary is used here is so negative numbers can be used as keys.

Alright, that makes sense. Well, thanks for your help! :slight_smile: