Unwanted behaviour from dict.fromkeys

后端 未结 5 650
感动是毒
感动是毒 2020-11-27 19:36

I\'d like to initialise a dictionary of sets (in Python 2.6) using dict.fromkeys, but the resulting structure behaves strangely. More specifically:



        
5条回答
  •  情书的邮戳
    2020-11-27 20:12

    Because of this from the dictobject.c:

    while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash))
    {
                Py_INCREF(key);
                Py_INCREF(value);
                if (insertdict(mp, key, hash, value))
                    return NULL;
    }
    

    The value is your "set([])", it is evaluated only once then their result object reference count is incremented and added to the dictionary, it doesn't evaluates it every time it adds into the dict.

提交回复
热议问题