Dictionary

Python Defaultdict vs Dictionary

In this tutorial, we will learn about Python Defaultdict vs Dictionary. Python provides both the built-in dict type (dictionaries) and the defaultdict class from the collections module. It offer similar functionality but with some differences in behavior. Let’s explore the differences between dict and defaultdict.

RELATED POST : How to Reverse the Python Dictionary?

What is Python Dictionary?

In Python, dictionaries represent a built-in data structure enabling you to store and organize data through key-value pairs. Often termed as associative arrays or hash maps in other programming languages, dictionaries uniquely associate each key with a specific value. This association enables swift retrieval of the corresponding value by utilizing the key, thereby rendering dictionaries highly advantageous for streamlined data retrieval and storage efficiency.

How to create and use of Dictionary in Python

1. Creating a Dictionary

To create a dictionary, utilize curly braces {} and separate key-value pairs with colons. You can employ various data types for both keys and values.

# Creating a dictionary with some key-value pairs
my_dict = {
    "name": "Rohan",
    "age": 30,
    "city": "Yamunanagar"
}

2. Accessing Values

To access the values in a dictionary, simply provide the corresponding key within square brackets [].

# Accessing values using keys
print(my_dict["name"])  # Output: Rohan
print(my_dict["age"])   # Output: 30

3. Adding and Modifying Entries

You can add new key-value pairs to a dictionary or modify existing entries.

# Adding a new entry
my_dict["occupation"] = "Engineer"

# Modifying an existing entry
my_dict["age"] = 31

4. Checking for Key Existence

To check if a key exists in the dictionary, you can use the in keyword.

if "name" in my_dict:
    print("Name is present:", my_dict["name"])

5. Removing Entries

To remove a key-value pair from a dictionary, you can use the del statement.

# Removing an entry
del my_dict["city"]

6. Iterating Through a Dictionary

You can iterate through a dictionary using loops.

# Iterating through keys
for key in my_dict:
    print(key, my_dict[key])

# Iterating through key-value pairs using items() method
for key, value in my_dict.items():
    print(key, value)

Dictionaries hold a versatile and vital role within Python, serving various purposes such as storing configurations, mapping data, and tallying element occurrences. Through their mechanism, they grant swift and efficient access to values, all contingent on their corresponding keys. This quality renders them indispensable instruments in a multitude of programming tasks.

Python Dictionary Example

# Creating a dictionary
student_info = {
    "name": "Rohan",
    "age": 25,
    "major": "Computer Science",
    "grades": [90, 85, 95]
}

# Accessing values using keys
print("Name:", student_info["name"])
print("Age:", student_info["age"])
print("Major:", student_info["major"])
print("Grades:", student_info["grades"])


Output:

Name: Rohan
Age: 25
Major: Computer Science
Grades: [90, 85, 95]

In this example, we’ve crafted a dictionary called student_info, incorporating a range of key-value pairs that encapsulate details about a student. Afterward, the program proceeds to extract and display distinct values from the dictionary, relying on their respective keys for retrieval. The outcome distinctly showcases the values linked to each dictionary key in the final output.

How to create and use Python defaultdict

A defaultdict belongs to Python’s standard library and comes from the collections module. It’s a type of dictionary that extends the basic dict with an ability to assign default values to missing keys.

1. Import the defaultdict class

To use defaultdict, start by importing it from the collections module.

from collections import defaultdict

2. Initialize a defaultdict with a default factory function

When initializing a defaultdict, you provide a default factory function as an argument. This function will be used to generate the default values for missing keys. Common factory functions include int, list, str, float, and more.

my_defaultdict = defaultdict(int)  # Default values will be integers (0 by default)
my_list_defaultdict = defaultdict(list)  # Default values will be empty lists
my_str_defaultdict = defaultdict(str)  # Default values will be empty strings

3. Using the defaultdict

You can use a defaultdict just like a regular dictionary. If you try to access a key that doesn’t exist, instead of raising a KeyError, a new key will be created with the default value generated by the factory function.

my_defaultdict["apple"] += 2  # Increment value of "apple" (starts at 0)
my_list_defaultdict["fruits"].append("banana")  # Append to the list under "fruits"
my_str_defaultdict["name"] += "John"  # Concatenate to the string under "name"

4. Nested Structures

defaultdict is often used to create nested data structures without explicitly creating inner dictionaries or lists. This is particularly handy for counting occurrences.

from collections import defaultdict

word_count = defaultdict(int)
text = "apple banana apple cherry banana"
words = text.split()

for word in words:
    word_count[word] += 1

print(word_count)

Output :

defaultdict(<class 'int'>, {'apple': 2, 'banana': 2, 'cherry': 1})

Python defaultdict Example

from collections import defaultdict

# Creating a defaultdict with int as the default factory
fruit_counts = defaultdict(int)
fruits = ["apple", "banana", "apple", "orange", "banana", "apple"]

# Count the occurrences of each fruit
for fruit in fruits:
    fruit_counts[fruit] += 1

# Display the fruit counts
for fruit, count in fruit_counts.items():
    print(f"There are {count} {fruit}s.")


Output:

There are 3 apples.
There are 2 bananas.
There are 1 oranges.

In this example, we import the defaultdict class from the collections module. We create a defaultdict named fruit_counts with int as the default factory. We then iterate through the list of fruits and use the fruit_counts dictionary to count the occurrences of each fruit. Finally, we print out the fruit counts using the items in the fruit_counts dictionary. Since we used int as the default factory, accessing a missing key initializes it with a default value of 0, allowing us to count the occurrences easily.

Python defaultdict Conclusion

In conclusion, the defaultdict is a powerful Python tool that efficiently manages default values for absent keys, offering a more elegant approach than traditional dictionaries. This becomes especially valuable when you’re aiming to establish nested structures, track occurrences, or manage instances where keys are missing in a more seamless manner.

Difference Between Python defaultdict and Dictionary

  • Default Values for Missing Keys:
    • In a regular dict, if you try to access a key that doesn’t exist, a KeyError is raised.
    • In a defaultdict, you provide a default value when initializing the dictionary. If you try to access a missing key, it will create the key with the default value instead of raising an error.
  • Initialization:
    • A dict is initialized using curly braces {} and key-value pairs.
    • A defaultdict is initialized by passing a default factory function (e.g., int, list, str, etc.) to it. The factory function determines the default value type for missing keys.
  • Usage:
    • Use a regular dict when you want a basic key-value storage without automatic default values for missing keys.
    • Use a defaultdict when you want to handle missing keys gracefully by providing default values, especially for use cases like counting occurrences or creating nested dictionaries.
  • Nested Structures:
    • defaultdict is often more convenient for creating and working with nested data structures, as you don’t need to explicitly create inner dictionaries or lists.
AspectDictionarydefaultdict
Default Values for Missing KeysRaises KeyError if key doesn’t existCreates key with default value if missing (no error)
InitializationCurly braces {} and key-value pairsDefault factory function sets default value type
UsageBasic key-value storageHandle missing keys gracefully, provide default values
Nested StructureExplicitly create inner structuresConvenient for nested structures, auto-creates

Conclusion

In conclusion, although both dict and defaultdict serve as containers for key-value pairs, the key difference lies in defaultdict allowing you to set default values for absent keys. This functionality streamlines your code and offers a more graceful approach to managing missing keys.

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Python Online Quiz

Level up your coding skills with our interactive programming quiz!