Overview
Dictionaries are Python's built-in mapping type that store key-value pairs. They are mutable, unordered (Python 3.7+ maintains insertion order), and highly optimized for lookups.
Creating Dictionaries
PYTHON
# Empty dictionary
empty_dict = {}
empty_dict = dict()
# Dictionary with initial values
person = {'name': 'John', 'age': 30, 'city': 'New York'}
# Using dict constructor
person = dict(name='John', age=30, city='New York')
# From list of tuples
pairs = [('a', 1), ('b', 2), ('c', 3)]
my_dict = dict(pairs)
# Dictionary comprehension
squares = {x: x**2 for x in range(6)}
Common Operations
Accessing Values
PYTHON
person = {'name': 'John', 'age': 30}
# Using square brackets
name = person['name'] # 'John'
# Using get() method (safer)
age = person.get('age') # 30
salary = person.get('salary', 0) # Returns 0 if key doesn't exist
Adding and Updating
PYTHON
person = {'name': 'John'}
# Add new key-value pair
person['age'] = 30
# Update existing value
person['name'] = 'Jane'
# Update multiple values
person.update({'city': 'Boston', 'age': 31})
# Merge dictionaries (Python 3.9+)
new_info = {'job': 'Developer'}
merged = person | new_info
Removing Items
PYTHON
person = {'name': 'John', 'age': 30, 'city': 'NYC'}
# Remove and return value
age = person.pop('age') # Returns 30
# Remove last inserted item (Python 3.7+)
item = person.popitem() # Returns ('city', 'NYC')
# Delete by key
del person['name']
# Clear all items
person.clear()
Dictionary Methods
PYTHON
d = {'a': 1, 'b': 2, 'c': 3}
# Get all keys
keys = d.keys() # dict_keys(['a', 'b', 'c'])
# Get all values
values = d.values() # dict_values([1, 2, 3])
# Get all key-value pairs
items = d.items() # dict_items([('a', 1), ('b', 2), ('c', 3)])
# Set default value
d.setdefault('d', 4) # Returns 4 and adds 'd': 4
# Copy dictionary
d_copy = d.copy()
Iteration
PYTHON
person = {'name': 'John', 'age': 30, 'city': 'NYC'}
# Iterate over keys
for key in person:
print(key)
# Iterate over values
for value in person.values():
print(value)
# Iterate over key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
Advanced Features
Nested Dictionaries
PYTHON
users = {
'user1': {'name': 'John', 'age': 30},
'user2': {'name': 'Jane', 'age': 25}
}
# Access nested values
john_age = users['user1']['age']
DefaultDict
PYTHON
from collections import defaultdict
# Automatically creates missing values
dd = defaultdict(list)
dd['fruits'].append('apple') # No KeyError
# Counter
from collections import Counter
words = ['apple', 'banana', 'apple', 'cherry']
counter = Counter(words) # Counter({'apple': 2, 'banana': 1, 'cherry': 1})
OrderedDict (Less relevant in Python 3.7+)
PYTHON
from collections import OrderedDict
# Maintains order of insertion
od = OrderedDict()
od['first'] = 1
od['second'] = 2
Performance Characteristics
- Lookup: O(1) average case
- Insert: O(1) average case
- Delete: O(1) average case
- Space: O(n)
Best Practices
1. Use get() method to avoid KeyError
2. Use dictionary comprehensions for creating dictionaries
3. Consider using defaultdict for nested structures
4. Use in operator to check key existence
5. Be cautious with mutable objects as keys (use immutable types)
Common Use Cases
- Configuration settings
- Caching and memoization
- Counting and grouping
- JSON data representation
- Database record representation