Concepts / Iterating Over Dictionaries

Iterating Over Dictionaries

Dictionaries are created empty using dict() or {} and store key-value pairs.

  • Programming
Interactive lab

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

  1. The for statement asks the object for an iterator, then calls next() on it once per pass.
  2. 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.
  3. 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).
  4. 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.
  5. 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.
  6. 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.

Educational simulation

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.

nameAdalanguagePythonlevelbeginnernextnext
What order are key-value pairs visited and displayed when a dictionary is iterated in Python 3.7 and later?

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.

Worked example

Adding Three Entries

Create an empty dictionary and add the entries name-Ada, language-Python, and level-beginner.

  1. 1
    Start empty

    Create the dictionary with dict() or with {}. At this point, it contains no key-value pairs.

  2. 2
    Add name

    Use square bracket assignment to associate the key name with the value Ada.

  3. 3
    Add language

    Use square bracket assignment to associate the key language with the value Python.

  4. 4
    Add level

    Use square bracket assignment to associate the key level with the value beginner.

Result

The dictionary contains three key-value pairs, ordered by the sequence in which they were added: name-Ada, language-Python, and level-beginner.

profilename: Adaprofilename: Ada, level: beginnerassign level
How does a dictionary change before and after assigning a value to a new key?

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.

StartnameAdalanguagePythonlevelbeginnerEndfirst entrynextnextno entries remain
What does the loop visit at each step, and how does control move from one dictionary entry to the next?

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?

  • first

  • second

  • third

Reveal answer
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.

Dictionary inputname: Ada, level: beginnernameAdalevelbeginnerDictionary outputname: Ada, level: beginnerstoresstoresappears asappears as
How do the key-value pairs written when creating a dictionary correspond to the pairs shown when it is printed or iterated?

Mistakes to Avoid

  • Common mistake

    Confusing an empty dictionary with a dictionary that already contains entries.

    What it looks like

    Starting with dict() or {} creates an empty container; it does not create key-value pairs.

    Why it fails

    The dictionary must receive entries after it is created.

    Do this instead

    Use square bracket assignment to add each key-value pair.

  • Common mistake

    Expecting dictionary entries to appear in an arbitrary order.

    What it looks like

    Assuming that an entry added third might be visited first.

    Why it fails

    Python 3.7 and later preserve insertion order.

    Do this instead

    Track 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 like

    Reading the shown key-value pairs without recognizing that the format can also be used as dictionary input.

    Why it fails

    The output format of a dictionary is valid input syntax for creating a dictionary with multiple items.

    Do this instead

    Use the displayed key-value structure to understand how the dictionary was represented and how multiple pairs can be supplied together.

Check Your Understanding

EASY

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.
  1. 1
    A 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.

More concepts starting with I