Python dictionary key error when assigning - how do I get around this?

ulak blade picture ulak blade · Jun 6, 2014 · Viewed 35.6k times · Source

I have a dictionary that I create like this:

myDict = {}

Then I like to add key in it that corresponds to another dictionary, in which I put another value:

myDict[2000]['hello'] = 50

So when I pass myDict[2000]['hello'] somewhere, it would give 50.

Why isn't Python just creating those entries right there? What's the issue? I thought KeyError only occurs when you try to read an entry that doesn't exist, but I'm creating it right here?

Answer

OldGeeksGuide picture OldGeeksGuide · Jun 6, 2014

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.