Skip to content

Instantly share code, notes, and snippets.

@Dowwie
Created February 12, 2015 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dowwie/218ca26ea08d399785a1 to your computer and use it in GitHub Desktop.
Save Dowwie/218ca26ea08d399785a1 to your computer and use it in GitHub Desktop.
How do YOU copy your dicts?
import timeit
import copy
from statistics import median, mean, stdev
def dictcopy1():
a = {'one': 1, 'two': 2, 'three': 3}
b = dict(a)
return b
def dictcopy2():
a = {'one': 1, 'two': 2, 'three': 3}
b = a.copy()
return b
def dictcopy3():
a = {'one': 1, 'two': 2, 'three': 3}
b = copy.copy(a)
return b
dicta = timeit.repeat("dictcopy1()", "from __main__ import dictcopy1",
repeat=100)
acopy = timeit.repeat("dictcopy2()", "from __main__ import dictcopy2",
repeat=100)
ccopy = timeit.repeat("dictcopy3()", "from __main__ import dictcopy3",
repeat=100)
print('\n', '*'*100)
print('b = dict(a)')
print('*'*100, '\n')
print('Median: ', median(dicta))
print('Mean: ', mean(dicta))
print('Sample StdDev: ', stdev(dicta)) # generalize population from sample
print('\n', '*'*100)
print('b = a.copy()')
print('*'*100, '\n')
print('Median: ', median(acopy))
print('Mean: ', mean(acopy))
print('Sample StdDev: ', stdev(acopy)) # generalize population from sample
print('\n', '*'*100)
print('b = copy.copy(a)')
print('*'*100, '\n')
print('Median: ', median(ccopy))
print('Mean: ', mean(ccopy))
print('Sample StdDev: ', stdev(ccopy)) # generalize population from sample
Results:
----------------------------------------------------------------------------------------------------------
****************************************************************************************************
b = dict(a)
****************************************************************************************************
Median: 0.42619629399996484
Mean: 0.4278273579900997
Sample StdDev: 0.006185062704368336
****************************************************************************************************
b = a.copy()
****************************************************************************************************
Median: 0.30548073149839183
Mean: 0.306699450550077
Sample StdDev: 0.004233703615272607
****************************************************************************************************
b = copy.copy(a)
****************************************************************************************************
Median: 0.8034708440027316
Mean: 0.8066223032602283
Sample StdDev: 0.00855569898601049
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment