3 Variants of Python Dictionaries That Make Your Coding Easier
Choose the most appropriate one
A dictionary in Python, which contains key-value pairs, is one of the key data structures for daily programming. Besides the basic dict
, Python kindly gives us more convenient options. Using them skillfully will make our code more elegant and our coding more smoothly.
This article will dive into 3 common used variants of Python dictionaries, from basic syntax to real scenarios. After reading, you will be able to choose the most appropriate one in real cases.
1. Defaultdict: Set a Default Value for Your Dict
When you get the value of a dict by a key, an unexpected exception may be raised:
>>> city = {'UK':'London','Japan':'Tokyo'}
>>> print(city['Italy'])# KeyError: 'Italy'
One solution to avoid the above issue is using the get()
function to require a value by a key:
city = {'UK':'London','Japan':'Tokyo'}
print(city.get('Italy'))# None
The get
function can return a None
instead of raising an exception when a key doesn’t exist.