From cd0887352d18467ea96728e75255ea36f425450d Mon Sep 17 00:00:00 2001 From: "John R. Lenton" Date: Mon, 6 Jan 2014 18:53:16 +0000 Subject: [PATCH] Added dict.get. --- py/objdict.c | 18 ++++++++++++++++-- tests/basics/tests/dict_get.py | 3 +++ 2 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 tests/basics/tests/dict_get.py 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) { diff --git a/tests/basics/tests/dict_get.py b/tests/basics/tests/dict_get.py new file mode 100644 index 0000000000..fb43a45eab --- /dev/null +++ b/tests/basics/tests/dict_get.py @@ -0,0 +1,3 @@ +for d in {}, {42:2}: + print(d.get(42)) + print(d.get(42,2))