0
0
PythonHow-ToBeginner · 3 min read

How to Create Dictionary with Default Value in Python

In Python, you can create a dictionary with a default value by using collections.defaultdict which automatically assigns a default for missing keys, or by using the dict.get() method to provide a default when accessing keys. Both methods help avoid errors when keys are not present.
📐

Syntax

There are two common ways to create a dictionary with default values:

  • Using defaultdict: You import defaultdict from collections and provide a function that returns the default value.
  • Using dict.get() method: You use get(key, default_value) to safely access keys with a fallback default.
python
from collections import defaultdict

# Using defaultdict
my_dict = defaultdict(lambda: 'default value')

# Using dict.get()
regular_dict = {'a': 1, 'b': 2}
value = regular_dict.get('c', 'default value')
💻

Example

This example shows how defaultdict automatically returns a default value for missing keys, and how dict.get() returns a default without raising an error.

python
from collections import defaultdict

# Create defaultdict with default string
my_dict = defaultdict(lambda: 'Not Found')
my_dict['apple'] = 10

print(my_dict['apple'])   # Existing key
print(my_dict['banana'])  # Missing key returns default

# Using dict.get()
regular_dict = {'apple': 10}
print(regular_dict.get('apple', 'Not Found'))  # Existing key
print(regular_dict.get('banana', 'Not Found')) # Missing key returns default
Output
10 Not Found 10 Not Found
⚠️

Common Pitfalls

One common mistake is trying to assign a default value directly in a normal dictionary, which does not work automatically for missing keys and raises a KeyError. Another is using mutable default values incorrectly with defaultdict, which can cause unexpected shared state.

Always use a function (like lambda) to provide default values in defaultdict to avoid shared mutable defaults.

python
from collections import defaultdict

# Wrong: Using mutable default directly (shared list)
wrong_dict = defaultdict(list)
wrong_dict['a'].append(1)
wrong_dict['b'].append(2)
print(wrong_dict)  # Works fine here but beware if default is mutable and reused

# Correct: Use lambda to create new list each time
correct_dict = defaultdict(lambda: [])
correct_dict['a'].append(1)
correct_dict['b'].append(2)
print(correct_dict)
Output
{'a': [1], 'b': [2]} {'a': [1], 'b': [2]}
📊

Quick Reference

Here is a quick summary of methods to create dictionaries with default values:

MethodDescriptionExample
defaultdictCreates dictionary with automatic default for missing keysdefaultdict(lambda: 0)
dict.get()Returns default value when key is missingmy_dict.get('key', default)
setdefault()Returns value if key exists, else sets and returns defaultmy_dict.setdefault('key', default)

Key Takeaways

Use collections.defaultdict with a function to create dictionaries with automatic default values.
Use dict.get(key, default) to safely access keys with a fallback default value.
Avoid assigning mutable default values directly in defaultdict to prevent shared state bugs.
dict.setdefault() can also set and return a default value for missing keys.
Normal dictionaries raise KeyError if you access missing keys without a default.