Fast way to copy dictionary in Python
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 contents. The copy will be edited and must not be linked to the original (e.g. changes in the copy must not affect the original.)
Keys are Strings, Values are Integers (0/1).
I currently use a simple way:
newDict = oldDict.copy()
Profiling my Code shows that the copy operation takes most of the time.
Are there faster alternatives to the dict.copy()
method? What would be fastest?
Solution 1:
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()
.
Solution 2:
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