Structuring Your Data

Dictionaries: Key-Value Thinking


Learning Objectives

  • You can create a dictionary with literal syntax and look up values by key.
  • You can add, update, and delete entries in a dictionary.
  • You can look up a key that might be missing using .get() and in.
  • You can iterate over a dictionary’s keys, values, and items.

A list maps positions to values. The position is the only handle you have on a value; sessions[0], row[1], and so on are the only ways to get at the data.

A dictionary, by contrast, maps names to values. You put things in a dictionary under a key of your choosing, and you get them back by that key: session["subject"], totals["math"].

Creating a Dictionary

The literal syntax uses curly braces, with key: value pairs separated by commas:

session = {
"subject": "math",
"minutes": 45,
"date": "2024-03-10",
}

This dictionary has three keys — "subject", "minutes", and "date" — each paired with a value. The keys here are strings, which is the most common case, though other types can be keys too.

You look up a value by putting its key in square brackets, like with list indexing, but with a key instead of a position:

print(session["subject"]) # math
print(session["minutes"]) # 45

Compare this to the list version of the same session:

row = ["math", 45, "2024-03-10"]
print(row[0]) # math -- you have to know subject is position 0
print(row[1]) # 45 -- and that minutes is position 1

With dictionaries, the key says what it means, while with lists, you have to remember what each position means. The minutes in session["minutes"] are easier to understand than the minutes in row[1], which only means “minutes” if you already know the layout.

An empty dictionary, which you build up later, is just {}:

totals = {}

Reading a named field

0 / 5 points

A book record is stored as {"title": "The Moon Gate", "pages": 240}.

Which expression reads the title field?

Missing Keys and KeyError

Python raises a KeyError if you try to look up a key that is not present:

print(session["duration"])
# KeyError: 'duration'

This is the dictionary equivalent of an IndexError on a list. Sometimes you do not know whether a key is present, and you want to handle the missing case without crashing.

The in operator checks whether a key exists:

if "duration" in session:
print(session["duration"])
else:
print("no duration recorded")

This is the same in operator you use to check whether an item is in a list. When working with dictionaries, it checks the keys, not the values. So "duration" in session is True if there is a key called "duration" — even if its value is None or 0 or some other “falsy” value.

When you want a value if it exists and a fallback if it does not, the .get() method does both in one step:

duration = session.get("duration", 0)

If "duration" is a key, .get() returns its value. If it is not, .get() returns the second argument — here, 0. If you call .get() with only a key and the key is missing, it returns None:

session.get("duration") # None, because there is no default given

Missing shelf

0 / 5 points

Some book dictionaries have a "shelf" key and some do not.

Which expression gives the shelf when present and "unknown" when missing?

Adding, Updating, and Deleting

Assigning to a key sets its value. If the key is new, it is added; if it already exists, its value is replaced:

session["minutes"] = 50 # updates an existing key
session["location"] = "library" # adds a new key

There is no separate “add” and “update” — assignment does both, depending on whether the key was already there. This is different from a list, where assigning to an index that does not exist (row[5] = 1 on a three-element list) is an error. A dictionary grows to fit whatever keys you assign.

To remove a key, use del:

del session["location"]

Deleting a key that is not present raises a KeyError. If you are not sure whether the item is there, check with in first.

if "location" in session:
del session["location"]

You can also use .pop() to remove a key and get its value at the same time:

location = session.pop("location", "unknown")

This removes the "location" key and returns its value if it exists. If it does not exist, it returns the second argument — here, "unknown". If you call .pop() with only a key and the key is missing, it raises a KeyError.

Iterating Over a Dictionary

Looping over a dictionary directly gives you its keys:

for key in session:
print(key)
# subject
# minutes
# date

This is occasionally what you want, but more often you want the keys and the values together, which is what .items() gives you:

for key, value in session.items():
print(f"{key}: {value}")
# subject: math
# minutes: 45
# date: 2024-03-10

Each step of the loop unpacks one key-value pair into two variables.

Two narrower methods exist for when you want only one side. .keys() gives just the keys, and .values() gives just the values:

for subject in totals.keys():
print(subject)
for total in totals.values():
print(total)

Looping over totals.keys() is the same as looping over totals directly, so the bare for key in totals form is more common. .values() is useful when you want to summarise the values without caring about the keys — for example, sum(totals.values()) to add up every total in the dictionary.


Dictionary Key Order

Since Python’s version 3.7, dictionaries remember the order in which the keys were added. When you iterate over a dictionary, you get the keys back in insertion order.

This is convenient and worth knowing. However, if you find that you want to know the order, you probably want a list instead — or you should sort the keys explicitly when you need them in a specific order.

Treat a dictionary as a tool for lookup by name, and reach for sorting when you need a particular order.

Check Your Understanding

  1. What is the difference between how a list finds a value and how a dictionary finds one?
  2. What does session.get("duration", 0) return if "duration" is a key? What does it return if it is not? And what does session.get("duration") return when the key is missing?
  3. You write session["location"] = "library" on a dictionary that has no "location" key. What happens? How is this different from assigning to an index that does not exist on a list?
  4. When you loop over a dictionary directly using for ??? in session, do you get keys, values, or key-value pairs in ????

AI Study Aid

Create a chapter diagram

We're looking into to what extent AI-generated diagrams could help with studying.

Use this study aid to generate an AI-generated visual summary of the material you just studied. Each diagram style emphasizes the content in a different way, so you can choose the focus that feels most useful.

Using the diagram generator is voluntary and does not affect your course progress. We encourage you to try it out and see if it helps, but it's totally up to you! Your answers help us understand how to make better study aids in the future.

Diagrams tried: 0