A dictionary in Python is a built-in dict type that stores data as key-value pairs and looks up a value by its key in average constant time. You create one with curly braces, for example {"name": "Ada", "age": 36}, and read a value with person["name"]. Since Python 3.7 a dictionary also remembers the order in which keys were inserted.
This guide covers creating dictionaries, reading and changing them, looping, comprehensions, merging with |, and the rules for keys. The examples run on Python 3.9 or newer; the merge operator needs 3.9.
Do not use dict.fromkeys(keys, []) with a mutable default, because every key then shares the same list.
Square brackets raise KeyError when the key is missing. Use get() or in when the key may be absent.
get() never changes the dictionary. setdefault(key, default) returns the value and also inserts the default when the key is missing.
popitem() removes in last-in, first-out order since Python 3.7. Use clear() to empty a dictionary.
keys(), values() and items() return live views, so they reflect later changes. Do not add or remove keys while iterating; Python raises RuntimeError: dictionary changed size during iteration. Loop over list(prices) if you need to modify it.
A comprehension builds a dictionary from any iterable.
Python 3.9 added the merge operators. When both sides share a key, the right-hand value wins.
Keys must be hashable, which means immutable types such as strings, numbers, tuples of hashable items and frozenset. Lists and dictionaries cannot be keys. Two keys that compare equal, like 1 and 1.0, count as the same key.
| Need | Tool |
|---|---|
| Count items | collections.Counter |
| Group values under a key | collections.defaultdict(list) |
| Read-only mapping | types.MappingProxyType |
| Typed fixed-shape records | typing.TypedDict |
Lookup, insert and delete take O(1) time on average. Iterating takes O(n).
Yes. Since Python 3.7 the language guarantees that a dictionary keeps insertion order. Two dictionaries with the same items still compare equal regardless of order.
A list is accessed by position, a dictionary by key. Use a dictionary when you look up values by name or identifier, and a list when order and position matter.
d.copy() or dict(d) makes a shallow copy, so nested objects are shared. Use copy.deepcopy(d) to copy nested structures.
Dictionaries cannot be sorted in place, but you can build a new one: dict(sorted(d.items(), key=lambda kv: kv[1])) sorts by value.
A Python dict maps hashable keys to values with fast average lookup and keeps insertion order. Use get() for safe reads, items() for loops, comprehensions to transform, and | to merge. Reach for Counter and defaultdict for counting and grouping.