Ad

What Is Easier For Machine - Dictionary Comprehension Or Deepcopy Of Existing Dictionary?

- 1 answer

Initializing a function I need two same dictionaries, one of them I can only create with dict. comprehension. But when it came to second one I got curious if it is easier (less time and/or fewer operations) for machine to make it as a deepcopy of the first one or rather repeat the same comprehension.

I usually set both as comprehensions 'cause my dictionaries are generally small, but when there are not empty values and/or more keys it may matter.

# both as comprehensions (implying I already have keys)
dict1 = {key: [] for key in keys}
dict2 = {key: [] for key in keys}

# second one as a deepcopy of the first
dict1 = {key: [] for key in keys}
dict2 = copy.deepcopy(dict1)

Well, I don't expect big difference for my case but I am just curious how it works in general.

Ad

Answer

deepcopy does a lot more work/checking than your first example, a simple timing exercise confirms this:

In [1]: import copy 
   ...:  
   ...: dict1 = {key: [] for key in 'abcdefgh'}    
   ...:  
   ...: %timeit dict2 = {key: [] for key in 'abcdefgh'} 
   ...:  
   ...: %timeit dict2 = copy.deepcopy(dict1) 
   ...:                                                                                                                                                                                                                                                                                   
816 ns ± 5.09 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
21 µs ± 28.6 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

If you know in advance your data structure (i.e. the level of nesting and types etc.), then you can make decent performance gains by avoiding deepcopy. However, deepcopy is more flexible of course.

Ad
source: stackoverflow.com
Ad