Python Defaultdict In Collections Tutorial – Complete Guide

Welcome to this exciting journey through the world of Python collections and particularly, the defaultdict. This Python functionality is a crucial element of the data structure known for its flexibility, performance, and efficiency. Let us unravel its utility and power through this comprehensive tutorial.

What is Python defaultdict?

The defaultdict is a specialized dictionary provided by the collections module in Python. Unlike standard dictionaries, defaultdict never raises a KeyError. Instead, it provides a default value for the key that does not exists.

Why is it Valuable?

Imagine you are designing a simple game where users collect various virtual items. Tracking these items and their count could become problematic with standard dictionaries when the player finds a new item and it’s not already in their collection.

Here defaultdict comes into the picture. The defaultdict is excellent for handling such scenarios efficiently. It simplifies your code and improves readability – two critical aspects of becoming a good programmer.

Why Must You Learn It?

Mastering defaultdict can lead to substantial improvements in your data wrangling and processing capabilities. Although at first glance the feature might seem trivial, its real power shines when dealing applications with complex data structures.

Whether you are a novice dipping your foot in the ocean of programming, or an experienced coder looking for more efficient solutions, learning defaultdict will undoubtedly take your Python skills to a new level.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

DefaultDict in Action

Let’s walk through a simple example of defaultdict. First, we’ll need to import it from the collections module.

from collections import defaultdict

Create a defaultdict. In the following example, we specify ‘int’ as the default_factory. This means that when a key is not present, Python automatically inserts that key with a default value of the result of int(), which is 0.

items = defaultdict(int)
print(items['sword'])  # Outputs: 0

Now, let’s add an item to our collection:

items['sword'] += 1
print(items['sword'])  # Outputs: 1

Even if we try to access a key that does not exist in the dictionary, we don’t get any error. Instead, Python creates that key with the default value 0:

print(items['staff'])  # Outputs: 0

Advanced Usage

If you want to use a data type other than an integer as the default value, you need to define a function that returns the desired value. Let’s see how we can use a list as the default value.

def default_value():
    return []

collections = defaultdict(default_value)
print(collections['sword'])  # Outputs: []

Say you want to add multiple values to a key, you can do that easily by appending to the list:

collections['sword'].append('Steel Sword')
collections['sword'].append('Golden Sword')
print(collections['sword'])  # Outputs: ['Steel Sword', 'Golden Sword']

Now, if we try to access a key that we haven’t used before:

print(collections['staff'])  # Outputs: []

As you can see, defaultdict is highly adaptable and a powerful tool in Python’s collections module!

Grouping with defaultdict

One of the most common uses of defaultdict is for grouping items. Let’s see how this can be done:

fruit_list = [('apple', 3), ('banana', 2), ('apple', 4), ('banana', 3), ('apple', 1), ('banana', 5)]
fruit_dict = defaultdict(list)
for key, value in fruit_list:
    fruit_dict[key].append(value)
print(fruit_dict)
# Outputs: defaultdict(, {'apple': [3, 4, 1], 'banana': [2, 3, 5]})

This code takes a list of fruit and their quantities and groups them into a defaultdict. The key is the fruit name, and the value is a list of quantities. For any new fruit, a new item would be created with the fruit name as the key and an empty list as the value.

Using lambda with defaultdict

You can use a lambda function to provide a default value in defaultdict. This is especially useful when you want a different default value from the basic int or list.

my_default_dict = defaultdict(lambda: 'Unknown fruit')
my_default_dict['apple'] = 'Apple'
print(my_default_dict['apple']) # Outputs: Apple
print(my_default_dict['banana']) # Outputs: Unknown fruit

The ‘lambda: ‘Unknown fruit” is a function that returns the string ‘Unknown fruit’. Therefore, when you access a key that does not exist, you will get ‘Unknown fruit’ as default value instead of an error.

Word Counting with defaultdict

Another popular use of defaultdict is to count the frequency of items. Here we will use the ‘int’ function as default, which initializes counting at 0.

words = ['apple', 'banana', 'apple', 'banana', 'apple', 'pear']
word_count = defaultdict(int)
for word in words:
    word_count[word] += 1
print(word_count)
# Outputs: defaultdict(, {'apple': 3, 'banana': 2, 'pear': 1})

Each time a word is found in the list, the count is incremented by one. If a new word is encountered that’s not already in the dictionary, it’s added with a default count of 0 before being incremented.

Switch Case in Python using defaultdict

Python doesn’t have a switch/case statement inbuilt. But with defaultdict, we can smartly emulate switch/case behavior:

def do_nothing():
    return "Invalid choice"
  
def eat_apple():
    return "Eating apple..."

def eat_banana():
    return "Eating banana..."
  
opt = defaultdict(lambda: do_nothing)
opt['1'] = eat_apple
opt['2'] = eat_banana

print(opt['1']())
# Outputs: Eating apple...

In this code snippet, we’ve set the default function to be ‘do_nothing’, which returns ‘Invalid choice’! If the user selects an invalid option, the default function will run.

Taking The Next Step in Your Python Journey

Congratulations on mastering defaultdict in Python! Now that you’ve equipped yourself with an essential Python collection, it’s time to take the next step in your programming journey.

We invite you to dive deeper into the world of Python with the Python Mini-Degree offered by Zenva Academy. This comprehensive collection of courses will take you beyond just the fundamentals of Python, helping you to master this versatile language quickly and efficiently.

Created for beginners and experienced programmers alike, our Python Mini-Degree teaches Python programming through hands-on projects where you will be creating your own games, algorithms, and real-world apps. This way, not only do you enhance your knowledge, but you also build an impressive portfolio of Python projects.

Python is widely used across various industry sectors, including data science, game development, robotics, and much more. By mastering Python, you’re opening the doors to a multitude of career opportunities, or expanding your existing skillset to stay current in your field.

We regularly update and expand our curriculum to make sure you are always updated with industry developments.

Beyond our Python Mini-Degree, we also offer a broader collection of Python Courses. These classes cater to a range of different Python-related topics and provide in-depth knowledge to help you become proficient in Python.

Conclusion

Aspiring coders and seasoned programmers alike can immensely benefit from mastering Python collections like defaultdict. An understanding of these tools will significantly boost your coding prowess, improve your efficiency, and open up a world of possibilities in your programming journey.

Ready to take the plunge and level up your Python skills? Opt for our Python Mini-Degree program at Zenva! Dive deeper into Python’s functionalities and power, unlock new realms of possibilities, and make your mark as an accomplished Python programmer. Happy coding!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.