Josef Kvita
Josef Kvita

Reputation: 156

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?

Upvotes: 2

Views: 1688

Answers (2)

iBug
iBug

Reputation: 37297

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.

Upvotes: 5

Daniele
Daniele

Reputation: 153

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.

Upvotes: 3

Related Questions