Dictionary iteration

Learn this with friends

ComputingIntro to computer science - Python5:266 check-ins

About this video

A for-each loop over a dictionary gives the next key on each iteration, in insertion order. The video shows the values() and items() methods for iterating by value or by key-value pair, how items are tuples that can be unpacked into two loop variables, and that these methods return efficient dictionary views.

You'll be able to

  • write a for loop that iterates over a dictionary by key, by value, or by item.
  • unpack a key-value tuple into two loop variables using items().
  • choose the iteration style that matches the data I need.
  • explain why casting a dictionary view to a list is unnecessary for iteration.

Key words

insertion order
The order in which items were added to a dictionary, which is the order Python loops over them.
tuple
An immutable list-like type written with parentheses; you can index into it but not change it.
variable unpacking
Assigning the elements of a tuple or list to several variables at once, like word, count = item.
dictionary view
The special iterable returned by keys(), values() and items() that peeks at the dictionary without copying it.
iterable
Any type you can loop over with a for loop.
Transcript

- [Instructor] How do we iterate over the items in a dictionary? There's no indices like enlists, so we can't use for I in range, but we can use a for each loop, we have the keyword for the loop variable name. the keyword in, and then the dictionary name followed as always by a colon.

But what do you think the loop variable holds on each iteration? When we iterate over a dictionary, the loop variable holds the next key. So we name our loop variable descriptively based on what the keys in the dictionary represent. Here, my dictionary keeps track of word frequencies in a text.

So my keys are all words, and my values are all counts. Python iterates over dictionaries in insertion order, meaning the order the items were added. So on the first iteration, the variable word will hold the key it. On the second iteration, it'll hold the key is, and on the third iteration, it'll hold the key, what.

And now that we've reached the end of the dictionary, the loop terminates. If I want the associated value inside the loop body, I just access it using the key. So now this prints out its value, two, is's value two. And then what's value, one. What if I wanna know what percentage of words were used more than once?

I need to keep track of the number of words whose count is greater than one. The total number of unique words is just the length of the dictionary. I'm using a very small dictionary here so we can trace it. But you can imagine this analysis will be a lot cooler with a dictionary with more words.

Notice that my loop body only really cares about the values and never uses the key on its own. For situations like this, Python provides two dictionary methods, values and items. There is also a keys method, though we don't need it here. This means we can iterate over a dictionary in three ways, by key, by value, and by item or key and value.

We can achieve all of the same things just by iterating by key, but these alternate syntaxes help make our code a bit cleaner depending on what we're trying to do. So back to our program, we can change it to iterate by value. We call the values method on our dictionary, and then we update our loop variable since now it represents the next value in the dictionary.

Okay, how about iterating by item? We call the items method on our dictionary, and then the loop variable holds the next item, meaning the next key value pair. But what data type is that? In Python, we call this a tuple. A tuple is just the immutable form of a list defined with parentheses instead of square brackets, we can index into a tuple, but we can't mutate it.

So if we wanna access the key, it'll be the first element in the tuple. And the value is the second element. A bit annoying to have to write that out because the key will always be at index zero and the value will always be at index one. Fortunately, Python gives us a shortcut called variable unpacking.

We can unpack an Iterable type, like a tuple or a list into several different variables, all in a single assignment. So we can unpack our item topple into its key and value by putting a comma in between the two variable names. Word will contain the first element and count will contain the second.

And to make this even easier, we can inline this unpacking into our for statement. On each iteration, the loop variable word contains the next key, and the loop variable count contains the next value. Be extra careful with the syntax, because it's easy to forget the comma or the dot items and end up with a weird error.

We can calculate the same result, just iterating by key. But if we need both the key and the value in the loop body, iterating by item often makes this a lot cleaner. So how do these methods actually work? The keys, values and items methods all return a special dictionary view type.

This is an Iterable type, meaning we can iterate over it, but it's not quite a list. Instead it's an optimized view into the existing dictionary. You can think of it like a special little window into the computer's memory where we can peek in on specific parts of the dictionary.

Like the values method gives us a window into just the dictionary values. We can cast a dictionary view to a list if we need to index into it, but if we're just iterating over it, the cast is not necessary. In fact, it's not optimal. As soon as we cast this dictionary view to a list, the computer copies over all of these values to a new location in memory.

Whereas if we just use the dictionary view directly, we're just peeking at the memory where the original dictionary is stored. Implementation aside, the big takeaway is that we can iterate over a dictionary by key, by value, and by item. The choice is just up to what data you need.

Video © Khan Academy, used under CC BY-NC-SA. Watch on Khan Academy. Puzzicle is not affiliated with Khan Academy.