Python Dictionaries
Beginner Data Structures

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.

GoalBy the end you can create a dictionary, read values with [] and get(), add, change and delete entries, loop over keys and values, and count things with a dictionary.

Before this lesson: Python for Loops, Python Lists

2Python Dictionaries: diagram

Python Dictionariesstudentkeys (unique)values (anything)"name""Asha""age"21"city""Pune""courses"["math", "art"]student["age"] → 21
Each key points to exactly one value. You ask for a value by its key, and Python jumps straight to it instead of searching from the start.

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.

Python
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:

Python
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

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.

Interactive example
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.

  1. Line 1A list of six votes, with some drinks repeated.
  2. Line 3An empty dictionary will hold one count per drink.
  3. 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 to counts[drink] creates or updates the key.
  4. Line 6The keys appear in the order they were first added: tea, coffee, juice.
  5. Line 8Square brackets read the value for a key that definitely exists.
  6. Line 9"water" isn't a key, so get() returns the default 0 instead of raising a KeyError.
  7. Line 10in checks the keys of the dictionary.
  8. Line 12-13update() changes the existing key "juice" to 2 and adds the new key "water" at the end.
  9. 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"])
KeyError: '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
TypeError: unsupported operand type(s) for +=: 'int' and 'str'

✓ 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]
RuntimeError: dictionary changed size during iteration

✓ 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

Change 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.

Your code
menu = {"tea": 1.5, "coffee": 2.0, "cake": 3.25}

# your code here

2. Predict the stock report

Predict the output Medium

Read the code and type exactly what it will print. Then press Check to run it and compare.

Read this code
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)

2 more exercises → 4 more examples

Finished this lesson?
Progress is saved in this browser — create a free account to keep it across devices.

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