A Dictionary Is a Lookup Table
Lists are indexed by position. Dictionaries are indexed by key — usually a string or a number — and each key maps to a value. That one shift unlocks a huge category of programs: inventories, configs, JSON payloads, user profiles, caches.
The keys and values can be almost anything. Keys need to be hashable (so: numbers, strings, tuples; not lists or other dicts). Values have no restriction — a dict can hold anything, including other dicts or lists.
Creating Dictionaries
Several ways, each with a place:
Reading Values
Two ways, and the choice matters:
Pick by intent:
- Use
[]when the key must be there. If it isn't, that's a bug and you want the loud error. - Use
.get()when "not present" is a valid case. It lets you write defaults without try/except.
Adding, Updating, Deleting
Assigning to a key either creates or updates it:
update() merges another dict or iterable of pairs:
Shared keys in overrides overwrite the ones in settings.
Checking for a Key
in checks the keys, not the values:
To check values specifically, use user.values():
How to Iterate a Dictionary
You have three views you can loop over:
.items() is what you reach for most of the time — it gives you the pair, unpacked, ready to use.
Iteration order in modern Python (3.7+) matches insertion order. A dict is not a "magic bag" — if you add a then b then c, iterating yields them in that order. That's a language guarantee you can rely on.
How to Sort a Dictionary
Dictionaries preserve insertion order, so "sorting" a dict really means building a new dict whose keys are inserted in the order you want:
sorted() returns a list of pairs; wrapping that in dict(...) reconstructs a dictionary with the new order. If you only need the sorted pairs (not a dict), skip the outer dict() call.
How to Merge Two Dictionaries
Python 3.9+ gives you the | operator:
Values from the right-hand dict win on key collisions. .update() is the in-place equivalent. On older Python versions, use {**defaults, **overrides}.
The setdefault Pattern
A common need: "if the key is there, use its value; if not, set a default and then use it."
Or, better, use collections.Counter:
Counter is a dict subclass that does counting by default. It's the right call whenever you're counting occurrences.
Dictionary Comprehensions
Parallel to list comprehensions, but for building dicts:
Same rules as list comprehensions, but with key: value between the braces.
Dict as JSON's Twin
Python dicts line up almost exactly with JSON objects. Converting between them is a single call:
This is why dicts show up everywhere in web work — your API requests and responses are basically dict manipulation with some network in the middle.
A Practical Example
A tiny config-like program that tracks a user profile:
Nested dicts, mutable values, .get() with a default — the basic toolkit for any record-shaped data.
Moving On
Lists, tuples, sets, dicts. With those four collections in hand, you can model almost any data you'll encounter early on. Next, we'll learn the list comprehension — Python's compact way to transform one collection into another.
Frequently Asked Questions
What is a dictionary in Python?
A dictionary is a collection of key-value pairs. You look up a value by its key — prices['apple'] instead of prices[0]. Dictionaries are fast to read and write, keys must be unique, and in modern Python they preserve the order you inserted items in.
How do I add a key to a Python dictionary?
Assign to it: my_dict['new_key'] = 'new value'. If the key already exists, the value is overwritten. If it doesn't, it's added. There's no distinction between "insert" and "update" — it's the same syntax.
What's the difference between dict[key] and dict.get(key)?
dict[key] raises KeyError if the key isn't there. dict.get(key) returns None (or a default you provide) instead. Use .get() when missing keys are expected and normal; use [key] when a missing key is a bug.