Python Dictionaries
1Python Dictionaries: overview
A dictionary stores pairs of keys and values, so you can look up a value by a meaningful key, such as a name or an ID, instead of by its position.
Before this lesson: Python for Loops, Python Lists
2Python Dictionaries: diagram
3Python Dictionaries: explained step by step
A dictionary (type dict) connects keys to values. Think of the contacts on your phone: you look up a name (the key) to find a number (the value). You write a dictionary with curly braces and key: value pairs separated by commas:
student = {"name": "Asha", "age": 21, "city": "Pune"}
empty = {}
Reading values
Put a key in square brackets to get its value: student["name"]. If the key isn't there, Python raises a KeyError. When a key might be missing, use get(), which returns None (or a default you choose) instead of crashing. To check whether a key exists, use in.
student = {"name": "Asha", "age": 21}
print(student["name"])
print(student.get("email"))
print(student.get("email", "not given"))
print("age" in student)Adding, changing and removing
Assigning to a key adds the pair if the key is new, or replaces the value if the key already exists. A key can appear only once. update() merges several pairs in at once, pop(key) removes a key and hands back its value, and del d[key] simply removes it.
What can be a key?
Keys must be immutable values such as strings, numbers or tuples, because Python finds them by their hash, just like set items. Values can be anything at all: numbers, lists, even other dictionaries. Dictionaries also remember the order in which keys were added, so printing and looping follow that order.
Looping
Looping over a dictionary gives you its keys. Use .values() to get just the values, or .items() to get (key, value) pairs that you can unpack right in the for line:
stock = {"apples": 12, "pears": 0, "plums": 7}
for fruit, count in stock.items():
print(fruit, "->", count)
print("Total:", sum(stock.values()))Nested dictionaries
A value can itself be a dictionary or a list. That's exactly how JSON data from web APIs looks. To dig in, chain the keys: users["u1"]["email"].
The counting pattern
Dictionaries are perfect for tallying. Use each item as a key and its count as the value. The expression counts.get(item, 0) + 1 handles both cases in one line: a new item starts from 0, and an existing one goes up by one.
Quick reference: Python Dictionaries
- Python Dictionary Cheat Sheet: Methods and Examples — A Python dictionary maps unique keys to values: read with `d[key]` or `d.get(key, default)`, add with `d[key]…
- Python List vs Dictionary: Differences and When to Use Each — A **list** stores values by position (`items[0]`), while a **dictionary** stores values by a meaningful key (…
- How to Remove Duplicates from a List in Python — Use `list(dict.fromkeys(items))` to remove duplicates **and keep the original order**. Use `list(set(items))`…
- How to Sort a Dictionary by Value in Python — Use `dict(sorted(d.items(), key=lambda item: item[1]))` to sort a dictionary by value, and add `reverse=True`…
- How to Merge Two Dictionaries in Python — Use `merged = a | b` (Python 3.9+) or `merged = {**a, **b}` to merge two dictionaries into a new one. If both…
- How to Read a CSV File in Python — Use the `csv` module: `with open("data.csv", newline="", encoding="utf-8") as f:` then `csv.DictReader(f)` gi…
- How to Read a JSON File in Python — Open the file and call `json.load()`: `with open("data.json", encoding="utf-8") as f: data = json.load(f)`. Y…
- How to Convert a List to a Dictionary in Python — Use `dict(zip(keys, values))` to build a dictionary from two lists, or `dict(list_of_pairs)` when each item i…
4Python Dictionaries: syntax
d = {key1: value1, key2: value2}
d[key] # read (KeyError if missing)
d.get(key, default) # read safely
d[key] = value # add or replace
key in d # does the key exist?
d.update(other) # merge in pairs
d.pop(key) # remove and return the value
for key, value in d.items():
5Python Dictionaries: run the example
Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.
votes = ["tea", "coffee", "tea", "juice", "coffee", "tea"]
counts = {}
for drink in votes:
counts[drink] = counts.get(drink, 0) + 1
print(counts)
print("Tea votes:", counts["tea"])
print("Water votes:", counts.get("water", 0))
print("Any juice?", "juice" in counts)
counts.update({"water": 2, "juice": 2})
print(counts)
for drink, total in counts.items():
print(f"{drink:<7}{'*' * total}")Expected output{'tea': 3, 'coffee': 2, 'juice': 1}
Tea votes: 3
Water votes: 0
Any juice? True
{'tea': 3, 'coffee': 2, 'juice': 2, 'water': 2}
tea ***
coffee **
juice **
water **
7Python Dictionaries: how the example works
Hover or tap a step to highlight its lines in the example above.
- Line 1A list of six votes, with some drinks repeated.
- Line 3An empty dictionary will hold one count per drink.
- Line 4-5For each vote,
counts.get(drink, 0)returns the current count (0 the first time a drink appears), and 1 is added. Assigning tocounts[drink]creates or updates the key. - Line 6The keys appear in the order they were first added: tea, coffee, juice.
- Line 8Square brackets read the value for a key that definitely exists.
- Line 9
"water"isn't a key, soget()returns the default 0 instead of raising aKeyError. - Line 10
inchecks the keys of the dictionary. - Line 12-13
update()changes the existing key"juice"to 2 and adds the new key"water"at the end. - Line 15-16
.items()gives each key and value together. The f-string pads the name to 7 characters and draws one star per vote.
8Python Dictionaries: common mistakes
Reading a key that doesn't exist
✗ Wrong
prices = {"apple": 0.5, "bread": 2.25}
print(prices["milk"])✓ Right
prices = {"apple": 0.5, "bread": 2.25}
print(prices.get("milk", "not sold here"))Check with in first, or use get() with a default value for keys that may be missing.
Expecting a loop to give you the values
✗ Wrong
ages = {"Asha": 21, "Ben": 19}
total = 0
for age in ages:
total += age✓ Right
ages = {"Asha": 21, "Ben": 19}
total = 0
for age in ages.values():
total += age
print(total)Looping over a dictionary gives its keys (the names here). Use .values() for the values, or .items() for both.
Deleting keys while looping over the dictionary
✗ Wrong
stock = {"pens": 0, "pads": 4, "tape": 0}
for item in stock:
if stock[item] == 0:
del stock[item]✓ Right
stock = {"pens": 0, "pads": 4, "tape": 0}
for item in list(stock):
if stock[item] == 0:
del stock[item]
print(stock)A dictionary can't grow or shrink while you are looping over it. Loop over a copy of the keys made with list(stock) instead.
9Python Dictionaries: exercises
Write your answer, then press Check. The checks run in your browser.
1. Update the cafe menu
Write code Easy ✓ CompletedChange the menu dictionary: add "juice" with the price 2.75, change the price of "coffee" to 2.25, then print how many items the menu has.
menu = {"tea": 1.5, "coffee": 2.0, "cake": 3.25}
menu["juice"] = 2.75
menu["coffee"] = 2.25
print(len(menu))
2. Predict the stock report
Predict the output Medium ✓ CompletedRead the code and type exactly what it will print. Then press Check to run it and compare.
stock = {"pens": 10, "pads": 4}
stock["pens"] = stock["pens"] - 3
stock["clips"] = 50
print(stock)
print(stock.get("tape", 0), len(stock))
for item in stock:
print(item){'pens': 7, 'pads': 4, 'clips': 50}
0 3
pens
pads
clips
2 more exercises → 4 more examples
Questions learners ask
What is the difference between d[key] and d.get(key)?
d[key] raises a KeyError when the key is missing, which is useful when a missing key means a bug. d.get(key) returns None instead, and d.get(key, default) returns your default. Use get() when a missing key is a normal situation.
Are Python dictionaries ordered?
Yes. Since Python 3.7, dictionaries keep keys in the order they were inserted, and printing or looping follows that order. You still can't read an item by position; you always use its key.
Can a dictionary have two identical keys?
No. Keys are unique: assigning to an existing key replaces its value. Values, however, can repeat as often as you like.
Further reading
10Next lesson
Up nextPython Dictionary MethodsDictionary methods are the built-in tools for everyday dictionary jobs: reading with a fallback, creating entries on fi…Related:
Python Dictionary MethodsPython Nested Data StructuresPython KeyError: What It Means and How to Fix ItWorking with JSON in Python
← Python Set Operations · All Data Structures lessons · Practise in the IDE