Find a course

Module 4: Lists, Dictionaries and Other CollectionsLesson 10 of 1213 min

Dictionaries, Tuples and Sets

Store key-value data in dictionaries, count things with them, use tuples for fixed groups of values, and remove duplicates and compare groups with sets.

Step 1 of 14Learn

Dictionaries: look things up by key

A list is great when position matters: first, second, third. But often you want to look something up by a name: the price of "coffee", the phone number of "Ana", the stock level of SKU "P-104". That's a dictionary (dict): a collection of key-value pairs.

prices = {"coffee": 3.50, "tea": 2.75, "cake": 4.25}
print(prices["tea"])           # 2.75
prices["juice"] = 3.95         # add a new pair
prices["coffee"] = 3.75        # update an existing value
del prices["cake"]             # remove a pair
print(len(prices))             # 3

Dictionaries use curly braces, with a colon between each key and its value. Keys are usually strings or numbers, and they must be unique: assigning to an existing key replaces its value. Values can be anything, including lists or other dictionaries.

Asking for a key that doesn't exist raises a KeyError. Two safe alternatives:

  • Check first: if "soda" in prices:. Note that in checks keys, not values.
  • Use get(): prices.get("soda") returns None instead of crashing, and prices.get("soda", 0) returns your chosen default, 0.

Dictionaries are fast: finding a key takes about the same time whether the dictionary holds ten items or ten million. Since Python 3.7 they also remember the order in which keys were added.

Step 2 of 14Practice · Diagram

Which collections are ordered or changeable?

Tap the region holding the collection that is indexed by position and can be changed.

Tap the shape that answers the question, then press Check.

Which collections are ordered or changeable?Venn diagram: Indexed, Changeable, Indexed only, Changeable + Indexed (overlap), Changeable only.IndexedChangeable• tuple• str• list• dict• set
Indexed

You can ask for item [0], [1], …

Changeable

Items can be added, removed or replaced.

Indexed only
  • tuple
  • str
Changeable + Indexed (overlap)
  • list
Changeable only
  • dict
  • set

Step 3 of 14Learn

Looping over dictionaries and counting things

Looping over a dictionary gives you its keys. Usually you want keys and values together, which is what .items() provides:

stock = {"apples": 12, "pears": 0, "plums": 7}
for fruit, qty in stock.items():
    if qty == 0:
        print(f"Reorder {fruit}")

.keys() and .values() give just one side: sum(stock.values()) is the total number of fruits, 19.

One of the most useful dictionary patterns is counting. Suppose you want to know how often each word appears in a sentence:

words = "the cat and the hat and the bat".split()
counts = {}
for w in words:
    counts[w] = counts.get(w, 0) + 1
print(counts)
# {'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}

For each word, counts.get(w, 0) returns the current count, or 0 the first time the word appears, and the line stores that number plus one. The same pattern counts votes, error types in a log file, sales per region or letters in a password.

Dictionaries can also be nested to describe structured records, such as {"name": "Ana", "skills": ["Python", "SQL"]}. This is exactly the shape of JSON data that web services send, which is why dictionaries are everywhere in real Python code.

Step 4 of 14Tap to reveal

Trace a counting loop over ["a", "b", "a"]

  1. Start

    counts = {}: an empty dictionary.

  2. Item "a"

    "a" is not a key yet, so counts.get("a", 0) + 1 stores 1: {"a": 1}.

  3. Item "b"

    New key: {"a": 1, "b": 1}.

  4. Item "a" again

    The key exists, so 1 + 1 = 2: {"a": 2, "b": 1}.

Step 5 of 14Practice · Code challenge · Python

Complete word_counts(text) so it returns a dictionary that maps each word to how many times it appears. Treat words as case-insensitive (convert to lowercase) and split on spaces with split(). For example, word_counts("to be or not to be") returns {"to": 2, "be": 2, "or": 1, "not": 1}.

Real Python, running in a sandbox in your browser.
  • word_counts("to be or not to be")
  • word_counts("Hi hi HI")
  • word_counts("one")
  • word_counts("")

Step 6 of 14Practice · What would you do?

What would you do?

What does this program print?

votes = ["red", "blue", "red", "green", "red", "blue"]
tally = {}
for v in votes:
    tally[v] = tally.get(v, 0) + 1
print(tally["red"], tally.get("yellow", 0))

Step 7 of 14Learn

Tuples: fixed groups of values

A tuple is like a list that can't be changed. It's written with parentheses (or just commas):

point = (3, 7)
rgb = (255, 128, 0)
date = 2026, 3, 15         # parentheses are optional
print(point[0])            # 3

Indexing, slicing, len, in and for loops all work, but point[0] = 5 raises a TypeError. Use a tuple when a group of values belongs together and shouldn't change: coordinates, an RGB color, a database row, a date.

Tuples power unpacking, which assigns several variables at once:

x, y = point                # x = 3, y = 7
name, age = ("Ana", 34)

You've already used this in for fruit, qty in stock.items() (each item is a tuple) and in swapping, a, b = b, a. Functions use it to return several values at once: return total, average actually returns one tuple, which the caller can unpack.

Because they can't change, tuples can be used as dictionary keys, which lists can't: distances[("Boston", "NYC")] = 215.

One quirk: a tuple with a single item needs a trailing comma, (5,). Without it, (5) is just the number 5 in parentheses.

Step 8 of 14Learn

Sets: unique items and fast membership

A set is an unordered collection with no duplicates:

tags = {"python", "data", "python", "web"}
print(tags)              # {'python', 'data', 'web'}  (order may vary)
tags.add("ai")
print("web" in tags)     # True

The fastest way to remove duplicates from a list is to convert it: set(emails). If you need a list again, wrap it: list(set(emails)). Be aware that sets don't keep order, so the result may come back shuffled.

Sets also make membership tests fast. Checking x in big_list looks at items one by one; x in big_set jumps straight to the answer. For a list of a few dozen items it doesn't matter; for a million it does.

Sets support the operations from math class, which answer real questions in one line:

OperationMeaningExample question
a.union(b)in either seteveryone who attended either event
a & bin both setscustomers who bought both products
a - bin a but not bsubscribers who haven't opened any email

The union also has a short operator form: a vertical bar between the two sets.

An empty set must be written set(), because {} creates an empty dictionary. And set items must be unchangeable values such as numbers, strings and tuples, so a set of lists isn't allowed.

Step 9 of 14Compare

Choosing a collection

AspectListTupleDictionarySet
Syntax[1, 2, 3](1, 2, 3){"a": 1, "b": 2}{1, 2, 3}
OrderedYesYesYes (insertion order)No
ChangeableYesNoYesYes (add and remove items)
DuplicatesAllowedAllowedKeys must be uniqueNot allowed
Access byPosition (index)Position (index)KeyMembership test only
Typical useA sequence of similar items: scores, tasksA fixed record: coordinates, a dateLookups by name or ID: prices, settingsUnique items and comparisons: tags, visitors

Step 10 of 14Practice · Sort into groups

Choose the best collection for each task.

Tap an item, then tap its group (or drag it there).

Step 11 of 14Note

Step 12 of 14Practice · True or false

A dictionary can hold two entries with the same key, as long as their values are different.

Step 13 of 14Practice · Choose one

What does {"a": 1, "b": 2}.get("c", 0) return?

Step 14 of 14Practice · Work it out

What is len(set([3, 1, 3, 2, 1, 3]))?