AI Hints
Home›Python Tutorial›Loops, Lists and Dictionaries
Python · Lesson 9 of 49

Dictionaries and Sets

Look things up instantly.

⏱ 3 min read▶ Video at 28:11🎓 Free
Watch this lesson in the Python courseWatch on YouTube ↗Full Python course

A customer asks, how much is the fern? With a list, Ava would scan every item until she found it. In a real phone book, you do not read every page. You look up a name, and jump straight to the number. Python has exactly that. It is called a dictionary.

Dictionaries and Sets
From the video: Dictionaries and Sets
  • The problem: searching a list is slow and awkward
  • The idea: look up by name, not position
  • The tool: the dictionary

A dictionary: keys and values

A dictionary stores pairs. Each key points to a value, written with a colon, inside curly brackets. Keys are unique, like names in a phone book. Here the keys are plant names, and the values are prices. Looking up a key is fast, even with millions of entries.

keyvalue
"fern"9.50
"ivy"7.00
"monstera"24.99
"cactus"12.00

Working with a dictionary

In the REPL, square brackets with a key give the value. Assigning to a new key adds a pair, and assigning to an existing key updates it. Asking for a missing key raises an error, so use the get method, which returns None, or a default you choose. The in operator checks for a key, and del removes one.

prices = {"fern": 9.5, "ivy": 7.0}
prices["fern"]
9.5
prices["cactus"] = 12.0
prices["ivy"] = 7.5
prices.get("rose", 0)
0
"fern" in prices
True
del prices["ivy"]
prices
{'fern': 9.5, 'cactus': 12.0}

Looping over a dictionary

To loop over a dictionary, use items, which gives each key and value together. You can also loop over just the keys, or just the values. Here Ava prints a price list, then calculates the value of her whole stock, by multiplying each price by the quantity on hand.

prices.pypython
prices = {"fern": 9.5, "ivy": 7.0, "cactus": 12.0}
qty = {"fern": 10, "ivy": 4, "cactus": 6}
for name, price in prices.items():
    print(f"{name:8} ${price:.2f}")
value = 0
for name in prices:
    value += prices[name] * qty[name]
print("Stock value:", value)
Output
fern     $9.50
ivy      $7.00
cactus   $12.00
Stock value: 195.0

Counting with a dictionary

Dictionaries are perfect for counting. Ava has a list of sold plants, and wants to know how many of each she sold. For each item, she adds one to its count, starting from zero when it is new. The get method with a default of zero makes it a one line job.

counting.pypython
sold = ["fern", "ivy", "fern", "cactus", "fern", "ivy"]
counts = {}
for item in sold:
    counts[item] = counts.get(item, 0) + 1
print(counts)
Output
{'fern': 3, 'ivy': 2, 'cactus': 1}

Nested data

Values can be anything, even lists, and other dictionaries. This is how real data looks, like a customer record. You reach inside by chaining square brackets. JSON, the format of the web, looks just like this. We will meet it again later.

nested_data.pypython
customer = {
    "name": "Maya",
    "orders": [24.99, 9.5],
    "address": {"city": "Leeds", "zip": "LS1"},
}
print(customer["name"])
print(customer["address"]["city"])
print(sum(customer["orders"]))
Output
Maya
Leeds
34.489999999999995

Sets: unique values

A set is a collection with no duplicates, and no order. Write it with curly brackets, but with no colons. Turning a list into a set removes repeated items instantly. Sets also do maths. Union combines two sets, intersection finds what they share, and difference finds what only one has. Checking membership in a set is very fast.

a = {"fern", "ivy", "rose"}
b = {"ivy", "rose", "tulip"}
set(["x", "y", "x", "x"])
{'y', 'x'}
a | b
{'fern', 'tulip', 'rose', 'ivy'}
a & b
{'rose', 'ivy'}
a - b
{'fern'}
"fern" in a
True

Phone book of plants

Your turn. Make a dictionary of three plants and their prices. Add a fourth plant, then print the price of one plant, and loop to print everything. Ready? Here is one solution. Curly brackets for the data, a new key, and items for the loop.

✍️ Exercise: Phone book of plants

Make a dict of 3 plants and prices, add a 4th, print one price, then print them all.

Show hint

prices[key] = value, then .items()

Show solution
phonebook.pypython
prices = {"fern": 9.5, "ivy": 7.0, "rose": 11.0}
prices["tulip"] = 6.5
print(prices["rose"])
for name, p in prices.items():
    print(name, p)
Output
11.0
fern 9.5
ivy 7.0
rose 11.0
tulip 6.5

Summary

Great job. Dictionaries map keys to values and look them up fast. You can add, update, delete, loop, and nest them. Sets hold unique values and do set maths. You now own the core data structures of Python. Next, Ava packages her code into reusable pieces, with functions.

Key takeaways
  • dict: key to value, fast lookups
  • get() gives safe defaults
  • set: unique values and set maths
Next up: Functions — write once, use everywhere