Fast way to copy dictionary in Python

后端 未结 6 971
广开言路
广开言路 2020-12-02 11:14

I have a Python program that works with dictionaries a lot. I have to make copies of dictionaries thousands of times. I need a copy of both the keys and the associated conte

6条回答
  •  情书的邮戳
    2020-12-02 11:39

    Looking at the C source for the Python dict operations, you can see that they do a pretty naive (but efficient) copy. It essentially boils down to a call to PyDict_Merge:

    PyDict_Merge(PyObject *a, PyObject *b, int override)
    

    This does the quick checks for things like if they're the same object and if they've got objects in them. After that it does a generous one-time resize/alloc to the target dict and then copies the elements one by one. I don't see you getting much faster than the built-in copy().

提交回复
热议问题