Iterating Over Dictionaries
Dictionaries are created empty using dict() or {} and store key-value pairs.
Try it: What a for Loop Hands You
What a Python for loop gives its loop variable from each kind of iterable: the characters of a string, the positions from range(len(word)), the elements of a list, (index, item) pairs from enumerate(), the numbers of range(start, stop, step), a dict's keys, its .values() and its .items() tuples unpacked into key, val, the inner lists of a nested list and the values an inner loop visits; and why removing items from a list while looping over it skips the next item, while looping over a copy nums[:] does not.
How it works
- The for statement asks the object for an iterator, then calls next() on it once per pass.
- Each next() result is bound to the loop variable (a tuple result such as ('a', 10) or (0, 'red') is unpacked into two names), and the indented body runs once with it.
- A string gives characters, a list gives element values (not positions), range() computes start, start + step, … stopping before stop, and a dict gives its keys in insertion order (.values() the values, .items() key-value tuples).
- A nested list's inner list is one element of the outer loop; a second, inner for loop is needed to visit the values inside it.
- A list iterator only remembers a position number into the live list: removing an item shifts the later items left, so the item that slides into the passed position is skipped. Looping over a copy (nums[:]) keeps the positions fixed.
- When next() has nothing left the loop ends (StopIteration) and the loop variable keeps its last value; an empty iterable runs the body zero times.
Default run (10 steps): A 3-line program. Step through it: each pass of the for loop asks the iterator for its next item, binds the loop variable to it and runs the indented body once. … Done: the loop body ran 3 times. Output: red | green | blue.
Simplified: The programs are twelve fixed templates: you choose the loop and edit only its data (a short string, list items that are words or integers, key: value pairs with word keys and integer values, range numbers from -20 to 20, up to 4 rows of integers, up to 10 numbers). Nothing you type is executed: the lab's own small parsers turn it into literals, and a model of CPython's iterator protocol written for these loops runs the program. Every program was also run in CPython 3.12 under sys.settrace, and the lab reproduces the variables before every line, the printed output, the final variables and the error.
Loading the simulation…
A Dictionary as Ordered Entries
A dictionary stores information as key-value pairs. Iterating over a dictionary means moving through the entries it contains. In Python 3.7 and later, those entries keep the order in which they were added, so the sequence used during iteration matches the insertion sequence.
Building the Dictionary
You can begin with an empty dictionary in either of two ways: dict() or {}. Both forms create an empty dictionary. After creating it, add a key-value pair with square bracket assignment. The general pattern is dictionary[key] = value. The key identifies the entry, and the value is the information stored for that key.
Adding Three Entries
Create an empty dictionary and add the entries name-Ada, language-Python, and level-beginner.
- 1Start empty
Create the dictionary with
dict()or with {}. At this point, it contains no key-value pairs. - 2Add name
Use square bracket assignment to associate the key name with the value Ada.
- 3Add language
Use square bracket assignment to associate the key language with the value Python.
- 4Add level
Use square bracket assignment to associate the key level with the value beginner.
The dictionary contains three key-value pairs, ordered by the sequence in which they were added: name-Ada, language-Python, and level-beginner.
Following the Iteration Sequence
Once a dictionary has several entries, iteration visits them in insertion order in Python 3.7 and later. If the entries were added in the order name, language, and level, iteration moves through name first, language second, and level third. The important idea is that the dictionary does not lose the sequence in which its entries were inserted.
What do you think happens?
A dictionary receives the entries first, second, and third in that order. Which entry is visited first during iteration in Python 3.7 and later?
Reveal answer
first
Python 3.7 and later preserve insertion order, so iteration follows the order in which the entries were added.
Reading Dictionary Output
A dictionary's output shows its key-value pairs in dictionary notation. That output format is also valid input syntax, which means a displayed dictionary with multiple pairs can be used to create a dictionary containing those pairs. The pairs shown in the output correspond to the pairs that were stored in the dictionary, and their displayed sequence follows insertion order in Python 3.7 and later.
Mistakes to Avoid
Common mistake Confusing an empty dictionary with a dictionary that already contains entries.
What it looks likeStarting with dict() or {} creates an empty container; it does not create key-value pairs.
Why it failsThe dictionary must receive entries after it is created.
Do this insteadUse square bracket assignment to add each key-value pair.
Common mistake Expecting dictionary entries to appear in an arbitrary order.
What it looks likeAssuming that an entry added third might be visited first.
Why it failsPython 3.7 and later preserve insertion order.
Do this insteadTrack the order in which entries are added and expect iteration to follow that sequence.
Common mistake Treating dictionary output as unrelated display text.
What it looks likeReading the shown key-value pairs without recognizing that the format can also be used as dictionary input.
Why it failsThe output format of a dictionary is valid input syntax for creating a dictionary with multiple items.
Do this insteadUse the displayed key-value structure to understand how the dictionary was represented and how multiple pairs can be supplied together.
Check Your Understanding
Describe the final dictionary and its iteration order after creating an empty dictionary, adding color-red, adding size-large, and adding status-ready in that sequence. Then explain how the dictionary's output format would represent those three pairs.
Hints
- List the entries in the order they were added.
- Remember that Python 3.7 and later preserve insertion order.
- The output represents the same key-value pairs stored in the dictionary.
- 1A dictionary can start empty with
dict()or {}. Add entries with square bracket assignment in the form dictionary[key] = value. In Python 3.7 and later, iteration follows insertion order. The dictionary representation shown as output contains the same key-value pairs and is also valid syntax for creating a dictionary with multiple items.
Key Takeaways
dict()and {} both create empty dictionaries.- Square bracket assignment adds key-value pairs.
- Python 3.7 and later preserve the order in which dictionary entries are inserted.
- Iteration and displayed output follow that insertion sequence.
- A dictionary's output format is also valid input syntax for creating multiple entries.