Skip to content

Commit f77dce8

Browse files
committed
Added dict.popitem
1 parent 0fcbaa4 commit f77dce8

2 files changed

Lines changed: 32 additions & 0 deletions

File tree

py/objdict.c

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,26 @@ static mp_obj_t dict_pop(int n_args, const mp_obj_t *args) {
186186
static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_pop_obj, 2, 3, dict_pop);
187187

188188

189+
190+
static mp_obj_t dict_popitem(mp_obj_t self_in) {
191+
assert(MP_OBJ_IS_TYPE(self_in, &dict_type));
192+
mp_obj_dict_t *self = self_in;
193+
if (self->map.used == 0) {
194+
nlr_jump(mp_obj_new_exception_msg(MP_QSTR_KeyError, "popitem(): dictionary is empty"));
195+
}
196+
mp_obj_dict_it_t *iter = mp_obj_new_dict_iterator(self, 0);
197+
198+
mp_map_elem_t *next = dict_it_iternext_elem(iter);
199+
self->map.used--;
200+
mp_obj_t items[] = {next->key, next->value};
201+
next->key = NULL;
202+
mp_obj_t tuple = mp_obj_new_tuple(2, items);
203+
204+
return tuple;
205+
}
206+
static MP_DEFINE_CONST_FUN_OBJ_1(dict_popitem_obj, dict_popitem);
207+
208+
189209
/******************************************************************************/
190210
/* dict constructors & etc */
191211

@@ -201,6 +221,7 @@ const mp_obj_type_t dict_type = {
201221
{ "copy", &dict_copy_obj },
202222
{ "get", &dict_get_obj },
203223
{ "pop", &dict_pop_obj },
224+
{ "popitem", &dict_popitem_obj },
204225
{ NULL, NULL }, // end-of-list sentinel
205226
},
206227
};

tests/basics/tests/dict_popitem.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
d={1:2,3:4}
2+
print(d.popitem())
3+
print(d)
4+
print(d.popitem())
5+
print(d)
6+
try:
7+
print(d.popitem(), "!!!",)
8+
except KeyError:
9+
print("Raised KeyError")
10+
else:
11+
print("Did not raise KeyError")

0 commit comments

Comments
 (0)