Dictionaries are one of Python's most powerful and versatile data structures. Their key-value pair system allows for flexible and efficient solutions to many common programming problems. Let's explore some key use cases.
Dictionaries are perfect for modeling real-world objects or structured data, much like JSON objects in web development.
# A dictionary representing a user's profile
user_profile = {
"user_id": 101,
"username": "alex_coder",
"email": "alex@example.com",
"is_active": True,
"permissions": ["read", "write"]
}
print(f"Username: {user_profile['username']}")
print(f"Permissions: {user_profile['permissions'][0]}")
A classic use case for dictionaries is to count the occurrences of items in a sequence.
text = "hello world"
char_counts = {}
for char in text:
char_counts[char] = char_counts.get(char, 0) + 1
print(char_counts)
Pro Tip: Use collections.Counter
for concise solutions:
from collections import Counter
text = "hello world"
print(Counter(text))
Dictionaries can act as a cache to store the results of expensive computations (memoization).
fib_cache = {}
def fibonacci(n):
if n in fib_cache:
return fib_cache[n]
if n <= 1:
return n
result = fibonacci(n - 1) + fibonacci(n - 2)
fib_cache[n] = result
return result
print(f"Fibonacci(35) = {fibonacci(35)}")
You can group items from a list based on a property using dictionaries.
students = [
{"name": "Alice", "grade": "A"},
{"name": "Bob", "grade": "B"},
{"name": "Charlie", "grade": "A"},
{"name": "David", "grade": "C"},
{"name": "Eve", "grade": "B"},
]
grades = {}
for student in students:
grade = student["grade"]
grades.setdefault(grade, []).append(student["name"])
print(grades)
Answer: Use either update()
or dictionary unpacking (**
).
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged1 = dict1.copy()
merged1.update(dict2)
merged2 = {**dict1, **dict2}
d[key]
and d.get(key)
?d[key]
: Raises KeyError
if missing.d.get(key, default)
: Returns default (or None
) if missing.d = {'a': 100}
print(d['a']) # 100
print(d.get('b')) # None
print(d.get('b', 0))# 0
scores = {'math': 95, 'science': 98, 'history': 88}
top_subject = max(scores, key=scores.get)
print(top_subject) # science