Advanced Dictionaries
Nested dicts, defaultdict, Counter, OrderedDict, and dictionary patterns.
Overview
Master advanced dictionary operations.
Nested Dictionaries
# Access nested values
config = {
"database": {
"host": "localhost",
"port": 5432,
"credentials": {
"user": "admin",
"pass": "secret"
}
}
}
# Safe access
def safe_get(d, keys, default=None):
for key in keys:
if isinstance(d, dict) and key in d:
d = d[key]
else:
return default
return d
print(safe_get(config, ["database", "host"])) # localhost
print(safe_get(config, ["database", "missing"])) # None
defaultdict
from collections import defaultdict
# Count occurrences
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
word_count = defaultdict(int)
for word in words:
word_count[word] += 1
print(dict(word_count)) # {'apple': 3, 'banana': 2, 'cherry': 1}
# Group by
students = [
("Alice", "Math"),
("Bob", "Science"),
("Charlie", "Math"),
("Diana", "Science"),
("Eve", "Math")
]
groups = defaultdict(list)
for name, subject in students:
groups[subject].append(name)
print(dict(groups))
# {'Math': ['Alice', 'Charlie', 'Eve'], 'Science': ['Bob', 'Diana']}
Counter
from collections import Counter
# Count elements
text = "hello world"
char_count = Counter(text)
print(char_count.most_common(3)) # [('l', 3), ('o', 2), ('h', 1)]
# Count list elements
fruits = ["apple", "banana", "apple", "cherry", "banana", "apple"]
fruit_count = Counter(fruits)
print(fruit_count["apple"]) # 3
# Update counters
counter1 = Counter(a=3, b=1)
counter2 = Counter(a=1, b=2)
print(counter1 + counter2) # Counter({'a': 4, 'b': 3})
print(counter1 - counter2) # Counter({'a': 2})
Dictionary Patterns
# Invert dictionary
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(inverted) # {1: 'a', 2: 'b', 3: 'c'}
# Merge dictionaries
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
# Python 3.9+
merged = dict1 | dict2
# Earlier versions
merged = {**dict1, **dict2}
print(merged) # {'a': 1, 'b': 3, 'c': 4}
# Filter dictionary
data = {"a": 1, "b": 2, "c": 3, "d": 4}
filtered = {k: v for k, v in data.items() if v > 2}
print(filtered) # {'c': 3, 'd': 4}
# Sort by value
sorted_dict = dict(sorted(data.items(), key=lambda x: x[1]))
print(sorted_dict) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Practice
Create a word frequency analyzer using Counter.