@@ -186,6 +186,26 @@ static mp_obj_t dict_pop(int n_args, const mp_obj_t *args) {
186186static 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};
0 commit comments