Invalid key error but only if nested dictionary

Hi humans
I'm trying to build a dictionary from a couple of named queries to provide information on the products used in the batch orders processed during a shift.
If I make a dictionary using the batch order codes as keys and the first piece of information I'm retrieving as values then it works fine.
If I try to use the batch order codes as keys, and then start a nested dictionary for all the batch information to be associated with the batch order key, I get a script-Eval error for "invalid key error".
(None of the batch order codes start with digits or contain special characters, vast majority are "BO" then 6 digits).

I don't understand why "BO000000" is a valid key for a {key:value} dictionary, but not for a {key:{key:value}} dictionary.

Code:

halfDict = {}
countDict = {}
halfList = []
for row in boSet:
	if row[1] != None:
		isHalf = system.dataset.toPyDataSet(system.db.runNamedQuery("ProjectScript/isHalf",{'barcode':row[1].split("-")[0]}))
		halfDict[str(row[0]).strip(" ")] = isHalf[0][0]
		countDict[str(row[0]).strip(" ")]['isHalf'] = isHalf[0][0]
	else:
		halfDict[str(row[0]).strip(" ")] = "u"
		countDict[str(row[0]).strip(" ")]['isHalf'] = "u"

Code will happily make 'halfDict' and return it, but gives an invalid key error on the BO codes for 'countDict'.
(The strip part doesn't actually make a difference, it's just to illustrate I've tried it...)

I've got the same dictionary setup code in another project and it's working fine.
Any hints as to where I'm being daft greatly appreciated.

halfDict[key] assigns a value to that key like you would expect.
On the other hand, countDict[key]['isHalf'] tries to access that key, which raises the KeyError.
This will NEVER work if key doesn't already exist in the dict.

There are solutions for this, like the dict setdefault method.

Why are you maintaining a second dict with the same keys ?
And, more generally, what are you trying to do ?

3 Likes

Hi Pascal
The other code isn't the same dictionary, it's just set up what I thought was the same way.
But isn't obviously, because for some reason I kept missing the line that assigns the nested dictionary keys.
Because I am a doofus.
headdesk
I'll take a look at setdefault as well.
Thanks