Python: Any use case for popitem()? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Python: Any use case for popitem()?

If popitem removes an arbitrary (key, value) pair from a (non-ordered) dictionary, what is it used for? Could anyone provide an example for practical application?

21st Mar 2020, 8:50 AM
Prof. Dr. Zoltán Vass
2 Answers
+ 2
'arbitrary' isn't true anymore since 3.7. 'Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order. popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError. Changed in version 3.7: LIFO order is now guaranteed. In prior versions, popitem() would return an arbitrary key/value pair.' https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
21st Mar 2020, 9:14 AM
HonFu
HonFu - avatar
0
HonFu Thanks! Is it also true for a non-ordered dictionary?
21st Mar 2020, 9:50 AM
Prof. Dr. Zoltán Vass