Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dict.popitem() in python 3.5

In the last versions of python, the builtin dictionary {} preserves the order, just like the OrderedDict (even if it's not guaranteed to do so).

Does dict.popitem() always return the last key-value pair from the dictionary, or a random one?

like image 687
Josef Kvita Avatar asked Apr 13 '26 15:04

Josef Kvita


2 Answers

Yes. From the Python Documentation (3.7):

popitem()

Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order.

The same also applies to collections.OrderedDict before Python 3.7.

However, do note that dict.popitem (the non-ordered version) has no guarantee in Python 3.6 or older versions.

like image 129
iBug Avatar answered Apr 15 '26 05:04

iBug


You mention python 3.5 (which is not the latest version), for which the docs say:

popitem()
Remove and return an arbitrary (key, value) pair from the dictionary.

where arbitrary means implementation dependent (possibly based on PYTHONHASHSEED), but not necessarily random or LIFO.

Since the latest python 3.7 however, like @iBug mentions, it's LIFO.

like image 37
Daniele Avatar answered Apr 15 '26 04:04

Daniele



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!