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

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds 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.

How to Use .popitem()

swannbouviermuller on Dec. 29, 2019

I find while True very ugly beacause we can’t understand up front when the loop will end. We have to read all the loop statements to find break(s) line.

I find “while len(a_dict) > 0:” much better.

Liam Pulsifer RP Team on Dec. 29, 2019

Thanks for the comment @swannbouviermuller. I generally agree with you. In this case, the while True: loop is intended to showcase the behavior of .popitem() when called on an empty dictionary (i.e. that it generates a KeyError), so it’s more of an illustrative example of a concept rather than an example of how you would structure a loop in practice. In the wild, your proposed loop condition is perfect!

cmansfield on Jan. 3, 2020

I’m not sure which version of Python you are using for this tutorial but from 3.7 popitem() removes the item last added to the list rather than a random key-value pair. I got suspicious after I kept getting the items returned / removed in this order and checked the documentation…

Liam Pulsifer RP Team on Jan. 3, 2020

Very nice catch @cmansfield. You are correct that in Python versions <= 3.6, .popitem() returned arbitrary items, but in 3.7 it was updated to return items in LIFO order. I’ll edit this video accordingly. Thanks again for the catch!

fjavanderspek on April 19, 2020

@swannbouviermuller we can even use

while a_dict: print(a_dict.popitem())

as an empty dictionary will evaluate to False

Become a Member to join the conversation.