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'))# NoneThe get function can return a None instead of raising an exception when a key doesn’t exist.
But if our program may need to require values by nonexistent keys many times. Another solution is to use the defaultdict:
from collections import defaultdict
city = defaultdict(str)
city['UK'] = 'London'print(city['Italy'])
#As shown above, we can determine what should be returned when defining a defaultdict. This is a good idea to avoid unexpected exceptions.
2. OrderedDict: Keep the Insertion Order of Your Dict
As its name implies, the OrderedDict is a dict whose key-value pairs’ insertion order will be kept. It will be super useful if the order is important.
from collections import OrderedDict
nums = OrderedDict()
nums['one'] = 1
nums['five'] = 5
nums['ten'] = 10
print(nums)
# OrderedDict([('one', 1), ('five', 5), ('ten', 10)])Fortunately, if you are using Python 3.7+, the insertion-order preservation nature applies to the normal dictionaries as well:
nums = dict()
nums['one'] = 1
nums['five'] = 5
nums['ten'] = 10
print(nums)
# {'one': 1, 'five': 5, 'ten': 10}However, there is one bug-prone point we should aware:
from collections import OrderedDict
nums1 = OrderedDict({'one': 1, 'five': 5, 'ten': 10})
nums2 = OrderedDict({'one': 1, 'ten': 10, 'five': 5})
print(nums1 == nums2)
# FalseThe above code compares two OrderedDict objects whose items are the same but the order of their items is different. The result is False.
How about normal dictionaries?
nums1 = {'one': 1, 'five': 5, 'ten': 10}
nums2 = {'one': 1, 'ten': 10, 'five': 5}
print(nums1 == nums2)
# TrueA little surprise? The above example (tested using Python 3.8) told us that normal dictionaries and OrderedDict objects are different, even on the versions of Python 3.7+.
Simply put, the order of items matters when comparing OrderedDict objects.
3. Counter: A Pythonic Way to Count Items
My favourite variant of Python dict is the Counter. Cause it can make our Python code shorter and more elegant.
For example, if we need to count how many times each letter is used in a piece of text, the most intuitive way may write a for loop to go through all letters and calculate the numbers.
But if you know Counter, the above task will be as simple as the following code:
from collections import Counter
title = "3 Variants of Python Dictionaries That Make Your Coding Easier"chars = Counter(title)print(chars)
# Counter({' ': 9, 'a': 6, 'i': 6, 'o': 5, 'r': 4, 'n': 4, 't': 4, 's': 3, 'e': 3, 'h': 2, '3': 1, 'V': 1, 'f': 1, 'P': 1, 'y': 1, 'D': 1, 'c': 1, 'T': 1, 'M': 1, 'k': 1, 'Y': 1, 'u': 1, 'C': 1, 'd': 1, 'g': 1, 'E': 1})As its name implies, the Counter object helps us do the calculation part and saves the results as a dictionary.
In addition, there is a very useful method in Counter called most_common().
Base on the previous code, if we want to print the first two letters that are used most often, the most_common() method can help:
print(chars.most_common(2))
# [(' ', 9), ('a', 6)]As shown above, this method can list the top n items and their counts from the most common to the least. (If n is None, it will list all items and counts from the most common to the least.)
Key Takeaways
- Use the
defaultdictvariant if you may require values by nonexistent keys. - Use the
OrderedDictvariant if the order of items matters. - Use
Countervariant to count items conveniently.
Thanks for reading. If you like it, please follow me and become a Medium member to enjoy more great articles about programming and technologies!
Relative articles:




