Skip to content

Commit cd08873

Browse files
committed
Added dict.get.
1 parent d90b19e commit cd08873

2 files changed

Lines changed: 19 additions & 2 deletions

File tree

py/objdict.c

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,20 @@ static mp_obj_t dict_copy(mp_obj_t self_in) {
140140
}
141141
static MP_DEFINE_CONST_FUN_OBJ_1(dict_copy_obj, dict_copy);
142142

143+
static mp_obj_t dict_get(int n_args, const mp_obj_t *args) {
144+
assert(2 <= n_args && n_args <= 3);
145+
assert(MP_OBJ_IS_TYPE(args[0], &dict_type));
146+
147+
mp_map_elem_t *elem = mp_map_lookup_helper(&((mp_obj_dict_t *)args[0])->map,
148+
args[1], false);
149+
if (elem == NULL) {
150+
return n_args >= 3 ? args[2] : mp_const_none;
151+
} else {
152+
return elem->value;
153+
}
154+
}
155+
static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_get_obj, 2, 3, dict_get);
156+
143157
/******************************************************************************/
144158
/* dict constructors & etc */
145159

@@ -153,6 +167,7 @@ const mp_obj_type_t dict_type = {
153167
.methods = {
154168
{ "clear", &dict_clear_obj },
155169
{ "copy", &dict_copy_obj },
170+
{ "get", &dict_get_obj },
156171
{ NULL, NULL }, // end-of-list sentinel
157172
},
158173
};
@@ -165,8 +180,7 @@ mp_obj_t mp_obj_new_dict(int n_args) {
165180
}
166181

167182
uint mp_obj_dict_len(mp_obj_t self_in) {
168-
mp_obj_dict_t *self = self_in;
169-
return self->map.used;
183+
return ((mp_obj_dict_t *)self_in)->map.used;
170184
}
171185

172186
mp_obj_t mp_obj_dict_store(mp_obj_t self_in, mp_obj_t key, mp_obj_t value) {

tests/basics/tests/dict_get.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
for d in {}, {42:2}:
2+
print(d.get(42))
3+
print(d.get(42,2))

0 commit comments

Comments
 (0)