Python dictionary key error when assigning - how do I get around this?
KeyError
occurs because you are trying to read a non-existant key when you try to access myDict[2000]
. As an alternative, you could use defaultdict:
>>> from collections import defaultdict>>> myDict = defaultdict(dict)>>> myDict[2000]['hello'] = 50>>> myDict[2000]{'hello': 50}
defaultdict(dict)
means that if myDict encounters an unknown key, it will return a default value, in this case whatever is returned by dict() which is an empty dictionary.
But you are trying to read an entry that doesn't exist: myDict[2000]
.
The exact translation of what you say in your code is "give me the entry in myDict with the key of 2000, and store 50 against the key 'hello' in that entry." But myDict doesn't have a key of 2000, hence the error.
What you actually need to do is to create that key. You can do that in one go:
myDict[2000] = {'hello': 50}
What you want is to implement a nested dict:
I recommend this approach:
class Vividict(dict): def __missing__(self, key): value = self[key] = type(self)() return value
From the docs, under d[key]
To try it:
myDict = Vividict()myDict[2000]['hello'] = 50
and myDict now returns:
{2000: {'hello': 50}}
And this will work for any arbitrary depth you want:
myDict['foo']['bar']['baz']['quux']
just works.