hbadger19042
hbadger19042

Reputation: 161

copying dictionary vs adding element to reconstruct dicionary

In python, I need to reconstruct a dictionary from an existing dictionary. The number of dictionary elements are around 5. I can make the new dictionary with the five elements or I can copy the existing dictionary.

Which method is faster between copying and making new one?

(I need to put this into for loop so it might big difference at the end.)

Example code:

orig = {'pid': 12345, 'name': 'steven king', 'country': 'usa', 'sex': 'M', 'company': 'MS'}

for _ in range(5000):

    copy1 = orig.copy()

    newone = {}
    newone['pid'] = 12345
    newone['name'] = 'steven king', 
    newone['country']= 'usa' 
    newone['sex'] = 'M'
    newone['company] = 'MS'

Upvotes: 0

Views: 31

Answers (1)

Jab
Jab

Reputation: 27495

There is one more way using argument unpacking

newone = {**orig}

Which you can also add new variables in that line:

newone = {**orig, 'newval': 'test'}

But from my simple tests the copy method seems to be the fastest:

from timeit import timeit

orig = {'pid': 12345, 'name': 'steven king', 'country': 'usa', 'sex': 'M', 'company': 'MS'}

def f1():
  newone = orig.copy()
  newone['newval'] = 'test'

def f2():
  newone = {}
  newone['pid'] = 12345
  newone['name'] = 'steven king', 
  newone['country']= 'usa' 
  newone['sex'] = 'M'
  newone['company'] = 'MS'
  newone['newval'] = 'test'

def f3():
  newone = {**orig, 'newval': 'test'}


print(timeit(f1))
print(timeit(f2))
print(timeit(f3))

Results:

1.4525865920004435
1.858240751986159
1.4954008519998752

Try here: https://repl.it/repls/NeglectedOrneryBash

Upvotes: 1

Related Questions