Python Dictionary Creation and Keys
Core idea
A dictionary maps keys to values. Use {key: value} with commas between entries. Look up a value by its key, not by its position. Keys must be hashable: strings, integers and tuples of hashable members are common choices. Values may be any objects. Use {} to start empty.
The key rice selects its associated count.
Build from pairs
pairs = [("red", 2), ("blue", 5)]counts = dict(pairs)print(counts)dict() accepts a sequence of two-item key-value pairs.
Repeated key
The later entry wins; there is only one tea key. len() counts entries.
Common mistake
A list cannot serve as a dictionary key because it is unhashable. Do not expect repeated equal keys to retain separate values.
Practice
Build a dictionary mapping two classroom labels to student counts. Retrieve one count.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dictionary creation
Check your understanding of dictionary creation.
What is printed?
print({"a": 1, "b": 2}["b"])What is printed?
print(len({"a": 1, "a": 2}))What is printed?
print(dict([("x", 4)]))Which cannot be a key in an ordinary dictionary?