Loading video player…

How to Iterate Through a Dictionary in Python: Overview

Dictionaries are one of the most important and useful data structures in Python. They can help you solve a wide variety of programming problems. This course will take you on a deep dive into how to iterate through a dictionary in Python.

By the end of this course, you’ll know:

  • What dictionaries are, as well as some of their main features and implementation details
  • How to iterate through a dictionary in Python by using the basic tools the language offers
  • What kind of real-world tasks you can perform by iterating through a dictionary in Python
  • How to use some more advanced techniques and strategies to iterate through a dictionary in Python

For more information on dictionaries, you can check out the following resources:

Ready? Let’s go!

Download

Sample Code (.zip)

4.7 KB
Download

Course Slides (PDF)

89.1 KB

Take the Quiz: Test your knowledge with our interactive “Python Dictionary Iteration” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

Python Dictionary Iteration

Dictionaries are one of the most important and useful data structures in Python. Learning how to iterate through a Dictionary can help you solve a wide variety of programming problems in an efficient way. Test your understanding on how you can use them better!

00:00 Hi everyone, and welcome to this Real Python video tutorial series on dictionary iteration. I’ve got my table of contents here, and so you can see what we’re going to be doing today, which is answering the question “What are dictionaries and why are we interested in them?” Really the question, I guess, is “Why should we care about dictionaries at all?” And to answer that, we’re going to get right into the Python interpreter in my terminal and take a look at some dictionaries and what’s interesting about them. So as you can see here, I’ve defined an example dictionary for us, and I’ve just done that so that we don’t have to deal with watching me type for an embarrassingly long period of time.

00:37 And what you’ll notice right away is that in a dictionary you have a key-value data structure separated by colons (:). So you have a pair, it’s essentially a list of pairs of keys to values.

00:50 And you can access these values using the keys, which is a really convenient thing. So if I do example at 'color', I get 'red', just as you just saw me do.

01:00 So, the question of why we care is really a question of why might we be interested in this kind of relationship system—a key related to a value. Well, the answer is that as nice as it is to have lists and variables and other Python data types, there are just a lot of kinds of data in the real world that require us to use some kind of relational structure. You might, for example, have a list of customers and you want each customer to map to the number of purchases they’ve made in the last month or something like that, right?

01:31 There are so many different possible applications for dictionaries. And what’s more, dictionaries are critically important to Python as a whole. Python as a language is really built on dictionaries.

01:40 For an example of that, let’s take a look at the local variables in this local context, using the locals() function, which is inbuilt to Python.

01:49 When you take a look at locals(), you can see here what we actually have is a dictionary!

01:55 You’ve got a giant dictionary with all of our local variables, and you can see a bunch of things I’ve used in this terminal session. I probably should have cleared this out. But you can see we have 'example', our dictionary. 'color' goes to 'red' and so on, it’s just the same as it is up there.

02:07 And so really, everything in Python—even down to the very low-level, the guts of Python—is implemented through dictionaries.

02:16 So, what really is a dictionary? We haven’t gotten totally into that. Well, you know you have to have keys and values. Well, what is a key? And what is a value? They’re really pretty simple.

02:27 Both can essentially be anything you want, except there’s one restriction on keys. Keys must be hashable. And I think it’s quicker to show you rather than to tell you what I mean.

02:37 So. I’m going to try to make a dictionary which maps a list to a string which says "HI!", just to say hello to you. And when I do that, we actually get a TypeError from Python because we have an unhashable type, a list, as one of the keys in our dictionary.

02:57 So, what is an unhashable type? Well, an unhashable type is something which does not have a .__hash__() function, and a possible reason—and the main reason why it might not have a .__hash__() function—is because an object is mutable. So for example, if I define a list l. It’s [1, 2, 3].

03:13 And then I say l[2] = 5, and then I print l, I have a different list object, right? And so the question here is if I were to use this as a key in a dictionary, once I make this change, what should map to "HI!"?

03:29 Should it be [1, 2, 3]? Should it be [1, 2, 5]? Should it be both, or neither? It’s really hard to tell, and it’s a difficult decision. And so, as in most cases when something is ambiguous, Python has decided that it’s best just to not let you do something, which I think is a wise design decision on the creators of Python’s part.

03:48 And so you can’t have unhashable types like lists as your keys. Values, on the other hand—you can have whatever the heck you want. So let’s put in 'HI' as my key, and it’s going to go to a value, which is this list that I keep using, [1, 2, 3].

04:03 And then we can say d['HI'], and we get the list right back. And it’s no problem, it works just fine. One way to get around this, if you’re having issues where you need to have something that’s list-like as a key in a dictionary, you can actually use a tuple.

04:18 And so what you can do here is you can say—

04:21 essentially, the difference is parentheses rather than square brackets, but tuples are immutable. You can’t do what I did above here with the l[2] trick. That doesn’t work with tuples. And so if I want to map this tuple to 5, that’s perfectly fine. And then I can access it again, just like this.

04:39 And so that’s one way to get around this problem.

04:43 So, dictionaries. Super useful because they are relational—they map keys to values. These keys have to be hashable, which normally means they have to be mutable, but the values can be whatever you want.

04:55 And if you need to get around this hashable key problem, then what you can do is you can use a hashable data type like a tuple. And for most objects you’ll use in Python that are unhashable, there is a hashable variant of them that just might be a little more difficult to work with. So, that’s dictionaries, that’s why they’re important, that’s why you might want to care about them, and that’s just a little bit of their inner functionality. Thanks.

Avatar image for solidgames

solidgames on Dec. 27, 2019

Keys must be hashes which normally means they have to be “mutable”? Don’t you mean keys are normally “immutable”.

Avatar image for Ajay

Ajay on Dec. 29, 2019

Keys in dictionary must be immutable.

Avatar image for Liam Pulsifer

Liam Pulsifer RP Team on Dec. 29, 2019

Yes indeed @solidgames and @ASK – I misspoke there.

Avatar image for Ajay

Ajay on Dec. 31, 2019

@Liam It was nice tutorial, learnt some new things.

Avatar image for Liam Pulsifer

Liam Pulsifer RP Team on March 18, 2020

If you’re confused at 3:10-3:25 when I say “a totally different list object,” what I meant there was that the contents of the list have changed, not that the id value of the object has changed or that I’ve created a new object. If you’d like more information on how this works, check out this tutorial realpython.com/python-is-identity-vs-equality/

Avatar image for kiran

kiran on Aug. 11, 2020

Can you make deep dive into hashable or give any resources for know more about hashables & unhashables in Python.

Avatar image for Bartosz Zaczyński

Bartosz Zaczyński RP Team on Aug. 11, 2020

We have a 3-minutes long explanation of the hashable objects by James: realpython.com/lessons/immutable-vs-hashable/

Become a Member to join the conversation.