diff options
author | John R. Lenton <jlenton@gmail.com> | 2014-01-06 18:53:16 +0000 |
---|---|---|
committer | John R. Lenton <jlenton@gmail.com> | 2014-01-07 22:51:08 +0000 |
commit | cd0887352d18467ea96728e75255ea36f425450d (patch) | |
tree | fca4c0cdb1438ed2b32a68fe7c31f01f1d58bb54 /py | |
parent | d90b19eca56a361d432ab6af9c2305bb3f708e1c (diff) | |
download | micropython-cd0887352d18467ea96728e75255ea36f425450d.tar.gz micropython-cd0887352d18467ea96728e75255ea36f425450d.zip |
Added dict.get.
Diffstat (limited to 'py')
-rw-r--r-- | py/objdict.c | 18 |
1 files changed, 16 insertions, 2 deletions
diff --git a/py/objdict.c b/py/objdict.c index 7567a612cd..fd5e37dfe0 100644 --- a/py/objdict.c +++ b/py/objdict.c @@ -140,6 +140,20 @@ static mp_obj_t dict_copy(mp_obj_t self_in) { } static MP_DEFINE_CONST_FUN_OBJ_1(dict_copy_obj, dict_copy); +static mp_obj_t dict_get(int n_args, const mp_obj_t *args) { + assert(2 <= n_args && n_args <= 3); + assert(MP_OBJ_IS_TYPE(args[0], &dict_type)); + + mp_map_elem_t *elem = mp_map_lookup_helper(&((mp_obj_dict_t *)args[0])->map, + args[1], false); + if (elem == NULL) { + return n_args >= 3 ? args[2] : mp_const_none; + } else { + return elem->value; + } +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_get_obj, 2, 3, dict_get); + /******************************************************************************/ /* dict constructors & etc */ @@ -153,6 +167,7 @@ const mp_obj_type_t dict_type = { .methods = { { "clear", &dict_clear_obj }, { "copy", &dict_copy_obj }, + { "get", &dict_get_obj }, { NULL, NULL }, // end-of-list sentinel }, }; @@ -165,8 +180,7 @@ mp_obj_t mp_obj_new_dict(int n_args) { } uint mp_obj_dict_len(mp_obj_t self_in) { - mp_obj_dict_t *self = self_in; - return self->map.used; + return ((mp_obj_dict_t *)self_in)->map.used; } mp_obj_t mp_obj_dict_store(mp_obj_t self_in, mp_obj_t key, mp_obj_t value) { |