Fast way to copy dictionary in Python

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

    The measurments are dependent on the dictionary size though. For 10000 entries copy(d) and d.copy() are almost the same.

    a = {b: b for b in range(10000)} 
    In [5]: %timeit copy(a)
    10000 loops, best of 3: 186 µs per loop
    In [6]: %timeit deepcopy(a)
    100 loops, best of 3: 14.1 ms per loop
    In [7]: %timeit a.copy()
    1000 loops, best of 3: 180 µs per loop
    

提交回复
热议问题