Useful Data Tips

Essential Python Dictionary Methods You Should Know

⏱️ 28 sec read 🐍 Python

Python dictionaries have powerful built-in methods that make your code cleaner and safer. Stop using basic indexing and master these:

1. get() - Safe Key Access

# Unsafe: KeyError if key missing ❌
value = my_dict['key']

# Safe: Returns None if missing ✅
value = my_dict.get('key')

# With default value
value = my_dict.get('key', 'default_value')

# Practical example
config = {'timeout': 30}
timeout = config.get('timeout', 60)  # 30
retries = config.get('retries', 3)   # 3 (default)

2. setdefault() - Get or Set

# Old way ❌
if 'count' not in stats:
    stats['count'] = 0
stats['count'] += 1

# Better way ✅
stats.setdefault('count', 0)
stats['count'] += 1

# Build grouped data
groups = {}
for item in data:
    groups.setdefault(item.category, []).append(item)

3. update() - Merge Dictionaries

# Add multiple items
user = {'name': 'John'}
user.update({'age': 30, 'city': 'NYC'})
# {'name': 'John', 'age': 30, 'city': 'NYC'}

# Merge dictionaries
defaults = {'timeout': 60, 'retries': 3}
custom = {'timeout': 30}
config = defaults.copy()
config.update(custom)
# {'timeout': 30, 'retries': 3}

# Python 3.9+ merge operator
config = defaults | custom

4. pop() - Remove and Return

# Remove key and get value
data = {'a': 1, 'b': 2, 'c': 3}
value = data.pop('b')  # Returns 2
# data is now {'a': 1, 'c': 3}

# With default (won't raise error)
value = data.pop('missing', 'default')  # Returns 'default'

# Remove last item (Python 3.7+, ordered)
key, value = data.popitem()  # ('c', 3)

5. keys(), values(), items()

person = {'name': 'Alice', 'age': 25, 'city': 'Boston'}

# Iterate keys
for key in person.keys():
    print(key)

# Iterate values
for value in person.values():
    print(value)

# Iterate key-value pairs (most common)
for key, value in person.items():
    print(f"{key}: {value}")

# Convert to list
keys_list = list(person.keys())
values_list = list(person.values())

6. fromkeys() - Create Dictionary

# Create dict with default values
keys = ['a', 'b', 'c']
default_dict = dict.fromkeys(keys, 0)
# {'a': 0, 'b': 0, 'c': 0}

# Initialize counters
counts = dict.fromkeys(['red', 'blue', 'green'], 0)

# Without default (values are None)
template = dict.fromkeys(['name', 'age', 'email'])

7. collections.defaultdict

from collections import defaultdict

# Auto-initialize missing keys
counts = defaultdict(int)  # Default to 0
for word in words:
    counts[word] += 1  # No need to check if key exists

# Group items
groups = defaultdict(list)
for item in items:
    groups[item.category].append(item)

# Nested dictionaries
matrix = defaultdict(lambda: defaultdict(int))
matrix[0][0] = 1  # Auto-creates nested structure

8. Practical Patterns

# Count occurrences
from collections import Counter
words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
counts = Counter(words)
# Counter({'apple': 3, 'banana': 2, 'cherry': 1})

# Filter dictionary
prices = {'apple': 1.2, 'banana': 0.5, 'cherry': 3.0}
cheap = {k: v for k, v in prices.items() if v < 2.0}

# Swap keys and values
inverted = {v: k for k, v in original.items()}

# Remove None values
cleaned = {k: v for k, v in data.items() if v is not None}

Best Practices

Pro Tip: Use collections.defaultdict when building dictionaries incrementally. It eliminates the need for "check if key exists" logic and makes code cleaner.

← Back to Python Tips