Fast way to copy dictionary in Python
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()
.
Appearantly dict.copy is faster, as you say.
[utdmr@utdmr-arch ~]$ python -m timeit -s "d={1:1, 2:2, 3:3}" "new = d.copy()"1000000 loops, best of 3: 0.238 usec per loop[utdmr@utdmr-arch ~]$ python -m timeit -s "d={1:1, 2:2, 3:3}" "new = dict(d)"1000000 loops, best of 3: 0.621 usec per loop[utdmr@utdmr-arch ~]$ python -m timeit -s "from copy import copy; d={1:1, 2:2, 3:3}" "new = copy(d)"1000000 loops, best of 3: 1.58 usec per loop
Can you provide a code sample so I can see how you are using copy() and in what context?
You could use
new = dict(old)
But I dont think it will be faster.