Dictionary setdefault and fromkeys
Core idea
d.setdefault(key, default) returns the existing value, or inserts and returns default if the key is absent. dict.fromkeys(keys, value) constructs a new dictionary with every key pointing to the same value object. The default for either method is None when omitted. For independent mutable groups, create a new list for each key.
groups = {}groups.setdefault("A", []).append("pen")groups.setdefault("A", []).append("pad")print(groups)The second call returns the existing list, so both items are retained.
Initialize numeric counts
counts = dict.fromkeys(["A", "B"], 0)counts["A"] = 2print(counts)Replacing the integer at A does not change B.
Avoid shared lists
shared = dict.fromkeys(["A", "B"], [])shared["A"].append(1)print(shared)separate = {}for key in ["A", "B"]: separate[key] = []separate["A"].append(1)print(separate)The first dictionary shares one list; the loop creates a distinct list each time.
Common mistake
setdefault(key, []) does not replace an existing None or other non-list value. When grouping, guarantee that existing values are lists. Do not initialize independent mutable groups with fromkeys and one list.
Practice
Group three (room, item) pairs by room using a loop and setdefault. Verify that adding an item to one group does not change another.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Setdefault and fromkeys
Check your understanding of setdefault and fromkeys.
What is printed?
d = {"x": 2}print(d.setdefault("x", 9))What is printed?
d = {}d.setdefault("x", 0)print(d)What is printed?
d = dict.fromkeys(["x", "y"], [])d["x"].append(3)print(d["y"])How do you initialize independent lists for several keys?