Skip to content

Commit 10a97e1

Browse files
authored
Remove the last element by popitem() (#1105)
It gives O(1) amortized complexity. The standard `dict.popitem()` removes the last entry also.
1 parent 6097b60 commit 10a97e1

File tree

4 files changed

+14
-7
lines changed

4 files changed

+14
-7
lines changed

CHANGES/1105.feature

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
:meth:`multidict.MultiDict.popitem` is changed to remove
2+
the latest entry instead of the first.
3+
4+
It gives O(1) amortized complexity.
5+
6+
The standard :meth:`dict.popitem` removes the last entry also.

multidict/_multidict_py.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -456,7 +456,7 @@ def popall(
456456
def popitem(self) -> tuple[str, _V]:
457457
"""Remove and return an arbitrary (key, value) pair."""
458458
if self._impl._items:
459-
i = self._impl._items.pop(0)
459+
i = self._impl._items.pop()
460460
self._impl.incr_version()
461461
return i[1], i[2]
462462
else:

multidict/_multilib/pair_list.h

+3-2
Original file line numberDiff line numberDiff line change
@@ -772,13 +772,14 @@ pair_list_pop_item(pair_list_t *list)
772772
return NULL;
773773
}
774774

775-
pair_t *pair = list->pairs;
775+
Py_ssize_t pos = list->size - 1;
776+
pair_t *pair = list->pairs + pos;
776777
PyObject *ret = PyTuple_Pack(2, pair->key, pair->value);
777778
if (ret == NULL) {
778779
return NULL;
779780
}
780781

781-
if (pair_list_del_at(list, 0) < 0) {
782+
if (pair_list_del_at(list, pos) < 0) {
782783
Py_DECREF(ret);
783784
return NULL;
784785
}

tests/test_mutable_multidict.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -158,8 +158,8 @@ def test_popitem(
158158
d.add("key", "val1")
159159
d.add("key", "val2")
160160

161-
assert ("key", "val1") == d.popitem()
162-
assert [("key", "val2")] == list(d.items())
161+
assert ("key", "val2") == d.popitem()
162+
assert [("key", "val1")] == list(d.items())
163163

164164
def test_popitem_empty_multidict(
165165
self,
@@ -546,9 +546,9 @@ def test_popitem(
546546
d.add("key", "val2")
547547

548548
pair = d.popitem()
549-
assert ("KEY", "val1") == pair
549+
assert ("key", "val2") == pair
550550
assert isinstance(pair[0], str)
551-
assert [("key", "val2")] == list(d.items())
551+
assert [("KEY", "val1")] == list(d.items())
552552

553553
def test_popitem_empty_multidict(
554554
self,

0 commit comments

Comments
 (0)