Skip to content

Commit d90b19e

Browse files
committed
Added dict.copy
1 parent 7d21d51 commit d90b19e

2 files changed

Lines changed: 15 additions & 0 deletions

File tree

py/objdict.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,15 @@ static mp_obj_t dict_clear(mp_obj_t self_in) {
130130
}
131131
static MP_DEFINE_CONST_FUN_OBJ_1(dict_clear_obj, dict_clear);
132132

133+
static mp_obj_t dict_copy(mp_obj_t self_in) {
134+
assert(MP_OBJ_IS_TYPE(self_in, &dict_type));
135+
mp_obj_dict_t *self = self_in;
136+
mp_obj_dict_t *other = mp_obj_new_dict(self->map.alloc);
137+
other->map.used = self->map.used;
138+
memcpy(other->map.table, self->map.table, self->map.alloc * sizeof(mp_map_elem_t));
139+
return other;
140+
}
141+
static MP_DEFINE_CONST_FUN_OBJ_1(dict_copy_obj, dict_copy);
133142

134143
/******************************************************************************/
135144
/* dict constructors & etc */
@@ -143,6 +152,7 @@ const mp_obj_type_t dict_type = {
143152
.getiter = dict_getiter,
144153
.methods = {
145154
{ "clear", &dict_clear_obj },
155+
{ "copy", &dict_copy_obj },
146156
{ NULL, NULL }, // end-of-list sentinel
147157
},
148158
};

tests/basics/tests/dict_copy.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
a = {i: 2*i for i in range(1000)}
2+
b = a.copy()
3+
for i in range(1000):
4+
print(i, b[i])
5+
print(len(b))

0 commit comments

Comments
 (0)