Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 769
ulak blade Avatar asked Jun 06 '14 19:06

ulak blade


People also ask

How do you bypass key errors in Python?

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.

Why am I getting a KeyError in Python?

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.

What happens if you try to access a dictionary key that doesn't exist?

If we try to access the value of key that does not exist in the dictionary, then it will raise KeyError.

How do you get a value from a dictionary in a way that doesn't raise an exception for missing keys in Python?

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.


2 Answers

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.

like image 198
OldGeeksGuide Avatar answered Sep 17 '22 13:09

OldGeeksGuide


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} 
like image 22
Daniel Roseman Avatar answered Sep 17 '22 13:09

Daniel Roseman