A review checklist begins with each section marked as pending.
What You Need to Understand
dict.fromkeys(iterable, value=None) builds a dictionary containing the supplied keys, each mapped to one shared supplied value.
When to Use It
A review checklist begins with each section marked as pending.
Step-by-Step Python Example
sections = ["content", "design", "testing"]
statuses = dict.fromkeys(sections, "pending")
print(statuses)
How the Example Works
The result has three different keys but the same immutable string value.
Example Output
{'content': 'pending', 'design': 'pending', 'testing': 'pending'}
{'a': [1], 'b': []}
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
keys = ["a", "b"]
data = {key: [] for key in keys}
data["a"].append(1)
print(data)
Important Behavior and Edge Cases
Using a mutable default such as [] shares the same list among every key; use a comprehension to create independent values.
Try It Yourself
Create independent empty task lists for three categories.
Common Beginner Mistakes
- Using a mutable default such as
[]shares the same list among every key; use a comprehension to create independent values. - Using the wrong collection method for this operation without checking whether it mutates the object, returns a result, or raises on missing data.
Key Takeaways
dict.fromkeys(iterable, value=None)builds a dictionary containing the supplied keys, each mapped to one shared supplied value.- The result has three different keys but the same immutable string value.
- Using a mutable default such as
[]shares the same list among every key; use a comprehension to create independent values.