How to Use .popitem()
So, it’s probably pretty clear to you—let’s do it again, just so we can see here what happens. Now we get
('apple', 'fruit') and
a_dict is reduced in size by one yet again, and this pair has been removed.
01:06 So, what you can probably tell is that what this does is it iterates destructively through a dictionary. And that means that it’s going to return and remove an item for you from the dictionary. So, you might be thinking, “Well, why is this useful?
01:22 I’m probably never going to need to use this.” Well, it could be very useful in some limited circumstances. For example, if you have a dictionary of items for which the ordering doesn’t really matter, and you know you’re not going to need to use it again.
And what this will allow you to do is if you have these conditions satisfied, then you can just iterate using
.popitem(), and then you are reducing the amount of memory you need to store stuff because if you’re just doing calculations on the things in your dictionary, then you can just pop all the items and not worry about it.
What happens if we try to pop an item again? Well, we get a
KeyError, because this dictionary was empty when we popped it. So, let’s redefine
a_dict. And this time, I’m just going to say,
'a' goes to
10, just for simplicity’s sake and ease of writing for me,
'b' goes to
'c' goes to
And this could continue, of course, but… So, we refilled
a_dict full of items, and I’ll show you a kind of a paradigm that’s useful for when you’re working with this
.popitem() function. What you can do is use a
while True: loop, which just continues to evaluate until you break out of it.
And then probably what you’ll do is you’ll do some cool stuff with this
item and then…Right. So, that’s good. And then we want to except the case that we get a
KeyError because of
.popitem() being called an empty dictionary.
And then finally, of course, we’ll break. So, this is a paradigm that’s really useful when you’re dealing with this
.popitem(), just because it gives you a nice way to iterate through destructively so that at the end you’ll have an empty dictionary, which will take up very little space, and then you’ll also have done all of the things you need to do with these items. So as you can see, we popped out here this, this, and then this.
And so the key things to remember with
.popitem() is that it’s a destructive iterator; that the exact items you get are not guaranteed, so be careful with assuming that there’s some kind of order that there really isn’t; and then you need to be careful at the end, because if you try to pop from an empty dictionary you’ll get a
Become a Member to join the conversation.