A Dictionary is a very useful and practical data structure. Dictionaries store data values in key-value pairs.
Dictionary is a collection which is ordered (as of Python 3.7), changeable and does not allow duplicates.
Python’s dictionary comes with many methods that make working with them easier, however as data gets more complex using them can also become challenging.
Let’s say you want to get a key that is not part of your dictionary.
|
|
Trying to access a key that does not exists results in KeyError which causes the program (unless you handle the error in some way) to crash.
That’s where built-in dictionary methods .get() and .setdefault() come very handy.
|
|
Using .get() method returns None when accessing key that does not exist. You can also specify second argument if you wish to return something else when the key does not exist.
If you want the count key and also put it in the dictionary if it’s not there already, you can use .setdefault() method.
|
|
These methods are very useful when you are for example building a dictionary on the go and want to avoid crashing the program in case the key does not exist.