Fast way to copy dictionary in Python

后端 未结 6 965
广开言路
广开言路 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:29

    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
    

提交回复
热议问题