A Wandering Mind · Computer Science
PYTHON GUIDE

Learn · Run · Break · Fix

A learning series from A Wandering Mind

Eighteen interlinked lessons on strings, lists, files, exceptions, and dictionaries—with original explanations, runnable examples, real output, and supporting CPSC 1301K lectures.

course.py
>>> guide = {
...   "lessons": 18,
...   "modules": 5,
...   "python": "3.10+"
... }
>>> guide["goal"] = "understand it"
Python Guide Lesson 16 of 18 Module 5 · Dictionaries ← Previous: Exceptions Next: Checking & Copying →
Module 5 · Dictionaries · Lesson 16 of 18

Dictionary Keys, Values, and Methods in Python

Lists organize values by numeric position. Dictionaries organize values by keys that carry meaning: a profile can store a value under "name", a settings object under "theme", or a score table under a person’s name. This lesson introduces dictionary literals, key-based lookup, adding and updating entries, and the core methods that expose keys, values, key/value pairs, and safe fallback lookups.

Prerequisite: Complete Handling Exceptions in Python. Dictionaries are another mutable built-in collection, so the list concepts from Module 2 will also help.

A dictionary maps keys to values

A dictionary is written with curly braces containing key: value pairs. The key identifies an entry; the value is the data associated with that key. Instead of asking for “item zero,” you can ask for the value stored under "name" or "level".

This makes dictionaries useful for records, configuration settings, counters, lookup tables, structured API data, and many other cases where meaningful labels are more useful than numeric positions.

Example 1 · Create and access a dictionaryVerified
profile = {
    "name": "Ada",
    "language": "Python",
    "level": 3
}
print(profile["name"])
print(profile["level"])
Ada
3

The strings "name", "language", and "level" are keys. Their associated values are "Ada", "Python", and 3. A dictionary value can be almost any Python object, including strings, numbers, lists, or even another dictionary.

Keys are not numeric positions. A dictionary key such as "name" identifies an entry directly. Dictionaries preserve insertion order in modern Python, but you should still think of lookup as key-based rather than positional.

Dictionary keys must be unique and hashable

Within one dictionary, each key identifies one current value. If you assign a new value to an existing key, that entry is updated rather than duplicated. Keys also have to be hashable, which means common immutable values such as strings, integers, and tuples can work as keys, while mutable lists cannot.

Values do not have the same restriction. Multiple keys can point to equal values, and values can be mutable objects.

Assignment updates an existing key or creates a new one

Dictionaries are mutable. Square-bracket assignment has two related behaviors: if the key already exists, its value changes; if the key is new, a new key/value pair is added.

Example 2 · Update one entry and add anotherVerified
settings = {"theme": "dark", "volume": 5}
settings["volume"] = 7
settings["captions"] = True
print(settings)
{'theme': 'dark', 'volume': 7, 'captions': True}

The "volume" key already existed, so its value changed from 5 to 7. The "captions" key did not exist, so Python added a new entry. No special add method is required for basic dictionary insertion.

keys(), values(), and items() expose dictionary views

Three foundational dictionary methods provide views over different parts of the mapping. keys() gives access to the keys, values() gives access to the values, and items() gives access to key/value pairs.

These methods return special view objects rather than ordinary lists. The views reflect the current dictionary. For teaching output below, list() converts each view into a list so its contents are easy to see.

Example 3 · Inspect keys, values, and pairsVerified
scores = {"Ada": 98, "Grace": 95, "Linus": 91}
print(list(scores.keys()))
print(list(scores.values()))
print(list(scores.items()))
['Ada', 'Grace', 'Linus']
[98, 95, 91]
[('Ada', 98), ('Grace', 95), ('Linus', 91)]

The pairs produced by items() appear as two-element tuples. This becomes especially useful in loops because one iteration can receive both the key and its associated value.

get() provides a safer lookup when a key might be absent

Square-bracket lookup is strict: mapping[key] raises KeyError when the key does not exist. The get() method is useful when absence is an ordinary possibility rather than an exceptional condition.

mapping.get(key) returns the stored value when the key exists and None when it does not. A second argument supplies a custom fallback.

Example 4 · Use get() with and without a fallbackVerified
inventory = {"camera": 2, "tripod": 1}
print(inventory.get("camera"))
print(inventory.get("lens"))
print(inventory.get("lens", 0))
2
None
0

The existing key returns its stored value. The absent key returns None when no fallback is supplied and 0 when that fallback is provided. Choosing between square brackets and get() depends on what absence means in your program: an unexpected missing key may deserve a visible error, while an optional field may deserve a default.

Direct lookupdata[key]

Returns the value for an existing key; raises KeyError if absent.

Add or updatedata[key] = value

Creates a new entry or replaces the current value for that key.

Safe fallbackdata.get(key, default)

Returns the stored value or the supplied default.

Pairsdata.items()

Produces a dynamic view of key/value pairs.

Looping over a dictionary usually means looping over keys or items

A plain for key in data: loop iterates over dictionary keys. If you need both sides of each mapping, for key, value in data.items(): is often clearer. The same unpacking idea appeared with enumerate() in the list module, but here the pair comes from each dictionary item.

This lesson stops short of dictionary membership tests because Lesson 17 is dedicated to checking dictionaries and understanding their reference/copy behavior. For now, the important foundation is knowing what a key is, what a value is, and how the main access methods represent the mapping.

Common dictionary mistakes

The failures below were executed in Python. They show four different assumptions that do not match dictionary rules.

Mistake 1 · Directly accessing a missing key
profile = {"name": "Ada", "language": "Python"}
print(profile["level"])
Traceback (most recent call last):
  File "/tmp/ipykernel_313/2116017354.py", line 12, in run_err
    exec(compile(code, filename, "exec"), {})
    ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/tmp/awm_lesson16/mistake1_missing_key.py", line 2, in <module>
KeyError: 'level'

Square-bracket lookup expects the key to exist. If absence is acceptable, use get() or explicitly test for the key in the next lesson.

Mistake 2 · Using a list as a dictionary key
lookup = {}
lookup[["red", "green"]] = "colors"
Traceback (most recent call last):
  File "/tmp/ipykernel_313/2116017354.py", line 12, in run_err
    exec(compile(code, filename, "exec"), {})
    ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/tmp/awm_lesson16/mistake2_unhashable_key.py", line 2, in <module>
TypeError: unhashable type: 'list'

Lists are mutable and therefore unhashable, so they cannot serve as dictionary keys. A tuple may be appropriate when you need an immutable multi-part key.

Mistake 3 · Treating a dictionary like a list
profile = {"name": "Ada"}
profile.append("Python")
Traceback (most recent call last):
  File "/tmp/ipykernel_313/2116017354.py", line 12, in run_err
    exec(compile(code, filename, "exec"), {})
    ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/tmp/awm_lesson16/mistake3_append.py", line 2, in <module>
AttributeError: 'dict' object has no attribute 'append'

Dictionaries do not have the list method append(). Add a key/value pair with assignment such as profile["language"] = "Python".

Mistake 4 · Passing too many arguments to get()
scores = {"Ada": 98, "Grace": 95}
print(scores.get("Ada", "missing", 0))
Traceback (most recent call last):
  File "/tmp/ipykernel_313/2116017354.py", line 12, in run_err
    exec(compile(code, filename, "exec"), {})
    ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/tmp/awm_lesson16/mistake4_get_too_many_args.py", line 2, in <module>
TypeError: get expected at most 2 arguments, got 3

get() accepts the key plus at most one default value. It is a focused lookup method, not a general multi-fallback function.

Supporting classroom explanations

This page is original A Wandering Mind instructional material. The two CPSC 1301K lectures below reinforce dictionary structure and the methods used to retrieve or work with dictionary data.

Introduction to Dictionaries — by Hyrum Carroll · 12:39. Watch on YouTube ↗ · CPSC 1301K playlist ↗

What it adds: a classroom introduction to key/value mappings and the basic syntax used to create and access dictionaries.

Dictionary Methods — by Hyrum Carroll · 5:56. Watch on YouTube ↗ · CPSC 1301K playlist ↗

What it adds: a focused overview of built-in methods that expose and retrieve dictionary information.

Try it yourself

For each exercise, identify which strings are keys and which objects are values before running the code.

Exercise 1 · Build a book record

Create a dictionary with "title" mapped to "Dune" and "year" mapped to 1965. Print both values using direct key lookup.

Show one answer
book = {"title": "Dune", "year": 1965}
print(book["title"])
print(book["year"])
Dune
1965

Exercise 2 · Update and add settings

Start with account = {"plan": "free"}. Change the plan to "pro", add "active": True, then print the dictionary.

Show one answer
account = {"plan": "free"}
account["plan"] = "pro"
account["active"] = True
print(account)
{'plan': 'pro', 'active': True}

Exercise 3 · Use a fallback price

Create prices = {"coffee": 4.5, "tea": 3.0}. Use get() to retrieve "tea", then retrieve missing "juice" with a fallback of 0.0.

Show one answer
prices = {"coffee": 4.5, "tea": 3.0}
print(prices.get("tea"))
print(prices.get("juice", 0.0))
3.0
0.0

What you should carry into Lesson 17

You now know how dictionaries map unique hashable keys to values, how square-bracket lookup retrieves an existing entry, how assignment adds or updates entries, and how keys(), values(), items(), and get() expose dictionary data in different ways.

Next, you will ask whether keys exist and revisit the reference/copy distinction from lists. Continue to Checking, Aliasing, and Copying Dictionaries.