avatarYang Zhou

Summary

The article discusses three Python dictionary variants: defaultdict, OrderedDict, and Counter, explaining their unique features and use cases to enhance coding efficiency.

Abstract

The article provides an in-depth look at three specialized Python dictionary types that offer distinct advantages over the standard dict. It begins by introducing defaultdict, which allows for setting default values to avoid key errors, and demonstrates its utility in scenarios where non-existent keys are frequently accessed. Next, the article covers OrderedDict, emphasizing its ability to maintain the insertion order of items, which is particularly useful when order matters, and notes that this feature is now standard in Python 3.7+ dictionaries. Lastly, it highlights the Counter class, which simplifies the task of counting item occurrences and offers a most_common() method for easily identifying the most frequent items. The article aims to equip readers with knowledge of these variants to write more elegant and efficient Python code.

Opinions

  • The author suggests that using defaultdict is a good practice to avoid unexpected exceptions when accessing keys that may not exist.
  • It is implied that the OrderedDict is useful for maintaining item order, but the author also points out a potential pitfall when comparing OrderedDict objects due to their order sensitivity.
  • The author expresses a preference for Counter, describing it as a favorite tool for counting items due to its simplicity and the powerful most_common() method it provides.
  • The author encourages readers to follow them and consider becoming Medium members to access more content on programming and technology.
  • The article promotes ZAI.chat as a cost-effective alternative to ChatGPT Plus (GPT-4), suggesting it as a valuable AI service for users interested in such tools.

3 Variants of Python Dictionaries That Make Your Coding Easier

Choose the most appropriate one

Photo by Hello Lightbulb on Unsplash

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.

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)
# False

The 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)
# True

A 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

  1. Use the defaultdict variant if you may require values by nonexistent keys.
  2. Use the OrderedDict variant if the order of items matters.
  3. Use Counter variant 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:

Programming
Python
Coding
Data Science
Technology
Recommended from ReadMedium