Open the contacts app on your phone. You do not scroll through numbers to find a person. You look up a name, and the phone gives you the number that belongs to it. A Python dictionary works the same way. It stores information as pairs, a name and its value, and lets you find any value instantly by asking for its name.
Dictionaries are one of the most useful data types in Python. They hold student records, product prices, settings for a program, counts of words in a text, and the data that web services send back as JSON. If you want to write real Python programs, you will use dictionaries in nearly every one.
In this tutorial, we start with what a dictionary is and how to create one. We then read values, change them, add new ones and loop through them, with every example run and its output shown. Next come the dictionary methods: get, values, items, len, pop, popitem, del and copy, plus others that the original version of this page missed, such as keys, update, setdefault and fromkeys. We finish with word counting, dictionary comprehension, nested dictionaries, the shallow copy trap, common errors and an FAQ.
A dictionary is a collection of key value pairs written inside curly braces. Each key is connected to one value, with a colon between them, and pairs are separated by commas.
Here the keys are 1, 2, 3 and 4, and the values are the short texts. Keys can be numbers, text, or tuples, and values can be anything at all.
Here is what makes a dictionary a dictionary:
All the outputs below came from a real run on Python 3.13. The same code works on every version from 3.7 onward.
Put the key inside square brackets. If the key does not exist, Python raises a KeyError. We will see how to avoid that when we reach the get method.
Use an equals sign. The original page wrote c[1] : ww with a colon, which does nothing. The colon belongs only inside the curly braces when you create the dictionary.
Assigning to a key that does not exist adds it.
A plain loop gives you the keys. Remember that the line inside a loop must be indented, which the original page missed.
Methods are built in tools that work on a dictionary. Here is the quick map before we try each one.
| Method | What it does | Returns |
|---|---|---|
| get(key) | Reads a value safely | The value, or None if missing |
| keys() | Lists the keys | A view of all keys |
| values() | Lists the values | A view of all values |
| items() | Lists key and value pairs | A view of pairs |
| pop(key) | Removes one item by key | The removed value |
| popitem() | Removes the last added item | The removed pair |
| update(other) | Adds or replaces many items | None, the dictionary is changed |
| setdefault(key, value) | Reads a key, adding it if missing | The value |
| clear() | Removes every item | None |
| copy() | Makes a shallow copy | A new dictionary |
| fromkeys(keys, value) | Builds a dictionary from keys | A new dictionary |
get reads a value by key without crashing when the key is missing. With square brackets, a missing key raises a KeyError. With get, you get None, or a default value that you choose.
values gives every value. Use it in a loop when you do not need the keys. The original page forgot the colon after the for line.
items gives each key and value together, so you can unpack both in one loop. The original example printed c[2] every time, which hid what items does. Print the two loop variables instead.
for key, value in c.items():
len counts the items, which means the number of key value pairs. You can also test whether a key exists with the in word, which checks keys and not values.
pop removes the item with the key you give, and hands back its value.
popitem removes the last item that was added and returns it as a pair. This order is guaranteed from Python 3.7. Before that, it removed an arbitrary item.
The original page shows c.del(), which is a syntax error. In Python, del is a statement, and not a method. Use del with a key to remove one item, or del with the dictionary name to delete the whole variable.
After del c, the name c no longer exists, and using it raises a NameError. If you want to empty a dictionary but keep it, use clear.
update adds the items of another dictionary. If a key already exists, its value is replaced.
From Python 3.9 you can also merge into a new dictionary with the vertical bar, which leaves the originals alone:
setdefault returns the value for a key. If the key is missing, it adds the key with the default you give, and returns that.
The first call added role. The second left city alone, because it was already there.
copy makes a new dictionary with the same items. But it is a shallow copy, which means that any list or dictionary stored as a value is shared between the original and the copy. The original page does not mention this, and it causes real bugs.
Adding 100 to the original list also changed the shallow copy, because both point to the same list. The deep copy was not affected. Use copy.deepcopy when your values are lists or dictionaries.
A very common job is counting how often things occur. The get method makes it short, because it returns 0 for a word seen for the first time.
You can build a dictionary in one line, in the same way as a list comprehension.
A value can be another dictionary. Use one pair of brackets for each level.
This is the shape of most JSON data from the web, so you will meet it often.
A key must be hashable, which in practice means it cannot be changed after it is created. Numbers, text and tuples work. A list does not, because a list can change.
| Mistake | What happens | Fix |
|---|---|---|
Reading a missing key with c[key] |
KeyError | Use c.get(key), or check with in first |
| Using a colon to change a value | Nothing changes | Use c[key] = value |
| Using a list as a key | TypeError, unhashable | Use a tuple |
| Changing a dictionary while looping over it | RuntimeError | Loop over list(c) or build a new dictionary |
| Treating copy as a full copy | Nested values are shared | Use copy.deepcopy |
Writing c.del() |
Syntax error | Use del c[key] |
| Forgetting indentation inside a loop | IndentationError | Indent the body by 4 spaces |
| Duplicate keys in one dictionary | The last one wins silently | Use unique keys |
| Type | Written as | Changeable | Best for |
|---|---|---|---|
| List | [1, 2, 3] | Yes | An ordered collection that grows or shrinks |
| Tuple | (1, 2, 3) | No | Fixed groups of values |
| Set | {1, 2, 3} | Yes | Unique items and quick membership checks |
| Dictionary | {“a”: 1} | Yes | Looking up values by a name or key |
The complete program below holds every example in this tutorial. Copy it into a file, run it, and compare your output with what you see above.
A dictionary is a simple idea that you will use every day: a name, and the value that goes with it. Run the examples, break them on purpose to see the errors, and then use dictionaries to count, group and look up your own data. When you are comfortable, move on to the other Python data types and to working with files and JSON.