How to use dictionary without 'KeyError' in python?
dict
is a built-in data type of Python that can store key and value combinations of data.
dict
d = {'count': 0}
print(d['count'])
>> 0
d['count'] += 1
print(d['count'])
>> 1
It can be used by mapping the value to the existing key as above.
print( d['name'] )
>> Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 1
Accessing a key that does not exist may throw a KeyError exception.
This is also the reason why you need to initialize the value to a specific key of the dictionary in order to use the dict without problems.
defaultdict
from collections import defaultdict
dd = defaultdict(int)
dd['count'] += 1
print( dd['count'] )
>> 1
So I prefer the defaultdict, which can be used without initializing the key.
It's good because you don't have to write logic to check and initialize the key whenever you need it.
... and it also improves code readability.
However, I think you can freely choose according to your code style.
More deeper
It was nice to use defaultdict without initializing a specific key.
but I thought,
Isn't it possible to use a deeper level without initializing it?
from collections import defaultdict
student = defaultdict()
student[1][3][21]['name'] = 'John'
>> Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 1
If you write it like the example above, you may get 'KeyError'.
Use factory function
from collections import defaultdict
def deeper():
return defaultdict(deeper)
d = deeper()
d['human']['name']['first'] = 'John'
print(d)
defaultdict(<function deeper at 0x7fbd70256cb0>, {'human': defaultdict(<function deeper at 0x7fbd70256cb0>, {'name': defaultdict(<function deeper at 0x7fbd70256cb0>, {'first': 'John'})})})
much better
when accessing an uninitialized {key:value}, you can lazyly assign a defaultdict.