Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Iterating Over Dictionaries

00:00 You may already know how to loop over lists and tuples. Just like lists and tuples, dictionaries are iterable too, so that means you can loop over them, for example with a for loop.

00:11 In this lesson, I will show you how to loop over dictionaries.

00:17 Let’s use the dictionary of US capitals again. When you loop over a dictionary with a for loop, you iterate over the dictionary keys, so for state in capitals:

00:35 Then indent. print(state) will print "California", "New York", and "Texas". What if you also want to print the city? Well, you already know how to access a value if you know its key, so you can adjust the print() call and write state, capitals

01:01 and then the state in square brackets ([]).

01:08 So when you run your code, you also print the capitals. So California Sacramento New York Albany and Texas Austin.

01:16 That works, but let me show you another way of accomplishing the same. This other way you will see more often in Python code. And that’s using the .items() dictionary method.

01:29 The .items() dictionary method returns a list-like object containing tuples of key-value pairs. That means you can loop over the keys and the values simultaneously.

01:41 Instead of having for state in capitals in line 7, you can now write for state, city in capitals.items(): print(state and now instead of capitals and [state], you can print the city. When you save and run it, then the output is exactly the same like before, but this code is considered more Pythonic.

02:14 Let me explain what happens under the hood. When you loop over capitals.items(), each iteration of the loop produces a tuple containing the state name and the corresponding capital city name.

02:27 By assigning this tuple to state, city in your for loop statement, you ensure that the components are unpacked into the two variables state and city. And that’s how you loop over a dictionary.

02:41 Next up, you will learn how to nest them.

Become a Member to join the conversation.