Structured lookup
Representing keyed application data such as configuration or records.
Python · Class
dict is Python’s mutable mapping type, associating hashable keys with arbitrary values. It supports construction from mappings, key-value pairs, and keyword arguments, plus dynamic key, value, and item views.
dict is Python’s mutable mapping type: it associates hashable keys with arbitrary values. Construct one from keyword arguments, another mapping, or an iterable of key-value pairs; access and modify entries with subscription, while keys(), values(), and items() provide dynamic views.
dict(**kwargs)
dict(mapping, **kwargs)
dict(iterable, **kwargs)| Name | Type | Description |
|---|---|---|
kwargs | keyword arguments | Keyword arguments used to create or update entries; keyword keys must be valid Python identifiers. |
mapping | mapping | A mapping whose entries are copied into the new dictionary. |
iterable | iterable of pairs | An iterable producing key-value pairs. |
A new dictionary object when called as a constructor.
scores = {"Ada": 10, "Grace": 12}
scores["Ada"] += 1
scores.setdefault("Lin", 0)
for name, score in scores.items():
print(name, score)Creates a mutable dictionary, updates an existing entry, initializes a missing key, and iterates over its item view.
Representing keyed application data such as configuration or records.
Counting, caching, or updating values by an identifier.
Iterating over keys, values, or pairs while observing later dictionary changes.
dict?A dictionary maps hashable keys to arbitrary values and is mutable. Keys identify entries, while values can be any objects.
Follow-up: What happens when two keys compare equal? They address the same dictionary entry; values such as 1, 1.0, and True can be interchangeable keys.
The constructor accepts keyword arguments, a mapping plus keyword arguments, or keyword arguments alone. It can also consume an iterable of key-value pairs.
Follow-up: When should you avoid keyword construction? Use another form when keys are not valid Python identifiers or when preserving arbitrary key objects matters.
keys(), values(), and items() return view objects rather than independent snapshots. Those views dynamically reflect later changes to the dictionary.
Follow-up: Which view has the unusual equality behavior? Comparing one dict.values() view with another always produces False.
dict.keys()dict.values()dict.items()dict.setdefault()Mapping