Skip to content

OrderedDict.fromkeys returns an (unordered) dict #12011

Description

@kbsriram
$ ./build-standard/micropython 
MicroPython v1.20.0-283-g7d66ae603-dirty on 2023-07-14; linux [GCC 7.5.0] version
Use Ctrl-D to exit, Ctrl-E for paste mode
>>> from collections import OrderedDict
>>> d = OrderedDict.fromkeys('abcdefg')
>>> ''.join(d)
'defagcb'
>>> type(d)
<class 'dict'>
>>> 

It looks like fromkeys is using mp_obj_new_dict

micropython/py/objdict.c

Lines 289 to 297 in 7d66ae6

mp_obj_t self_out;
mp_obj_t len = mp_obj_len_maybe(args[1]);
if (len == MP_OBJ_NULL) {
/* object's type doesn't have a __len__ slot */
self_out = mp_obj_new_dict(0);
} else {
self_out = mp_obj_new_dict(MP_OBJ_SMALL_INT_VALUE(len));
}
but missing the extra OrderedDict related initializations used in the actual constructor

micropython/py/objdict.c

Lines 115 to 122 in 7d66ae6

mp_obj_t dict_out = mp_obj_new_dict(0);
mp_obj_dict_t *dict = MP_OBJ_TO_PTR(dict_out);
dict->base.type = type;
#if MICROPY_PY_COLLECTIONS_ORDEREDDICT
if (type == &mp_type_ordereddict) {
dict->map.is_ordered = 1;
}
#endif

I see some larger plans to possibly normalize dict and OrderedDict in #6170 - in the interim, can you use a small fix PR for this current issue? It also seemed mostly independent from the changes in #6173

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugpy-coreRelates to py/ directory in source

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions