Unpacking Dictionary ItemsΒΆ

A dictionary consists of key-value pairs. When you call the items() method on a dictionary, you get back a list of key-value pairs. Each of those pairs is a two-item tuple. (More generally, we refer to any two-item tuple as a pair). You can iterate over the key-value pairs.

Each time line 4 is executed, p will refer to one key-value pair from d. A pair is just a tuple, so p[0] refers to the key and p[1] refers to the value.

That code is easier to read if we unpack the key-value pairs into two variable names.

More generally, if you have a list of tuples that each has more than two items, and you iterate through them with a for loop pulling out information from the tuples, the code will be far more readable if you unpack them into separate variable names right after the word for.

Next Section - Glossary