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?
Avoiding KeyError when accessing Dictionary Key We can avoid KeyError by using get() function to access the key value. If the key is missing, None is returned. We can also specify a default value to return when the key is missing.
A KeyError generally means the key doesn't exist. So, are you sure the path key exists? Raised when a mapping (dictionary) key is not found in the set of existing keys. So, try to print the content of meta_entry and check whether path exists or not.
If we try to access the value of key that does not exist in the dictionary, then it will raise KeyError.
If you want to get None if a value is missing you can use the dict 's . get method to return a value ( None by default) if the key is missing. To just check if a key has a value in a dict , use the in or not in keywords.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With