Search code examples
pythondictionarytimertimeitdel

Timing del operator on dictionaries, KeyError?


I've been working on a python assignment for a class I'm taking and I just can't figure out how to get past this KeyError. I'm trying to time the use of the del operator on dictionaries in python, here is my code:

from timeit import Timer


def build_dict(n): # build dict = { 0:"0", 1:"1", 2:"2", ... n:"n" }
    return {i : str(i) for i in range(n)}  

def dictionaryx(x,n):
    del x[0]
    del x[n//2]
    del x[n-1]

timeDict = Timer(
    "dictionaryx(x,n)",
    "from __main__ import n,build_dict,dictionaryx; x = build_dict(n)")


for size in range(1000, 100000+1, 5000):
    n = size
    dict_secs = timeDict.repeat(5,5)
    print(n, "\t", min(dict_secs))

Every time I try to run this code I get following error

Traceback (most recent call last): File "/Users/mcastro/PycharmProjects/untitled1/testdel.py", line 21, in dict_secs = timeDict.repeat(5,5) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/timeit.py", line 206, in repeat t = self.timeit(number) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/timeit.py", line 178, in timeit timing = self.inner(it, self.timer) File "", line 6, in inner File "/Users/mcastro/PycharmProjects/untitled1/testdel.py", line 10, in dictionaryx del x[0] KeyError: 0

I can't figure out why I'm getting this error or how to fix it, as far as I understand the keys the errors are referencing are present but can't be deleted? Any help would be much appreciated


Solution

  • Your timeit loop is using the same dictionary x every time. The first time you call dictionaryx(x,n), it deletes element 0 so it's not there the next time you call it.

    def build_dict(n): # build dict = { 0:"0", 1:"1", 2:"2", ... n:"n" }
        return {i : str(i) for i in range(n)}
    
    def dictionaryx(x,n):
        del x[0]
        del x[n//2]
        del x[n-1]
    
    n = 1000
    x = build_dict(n)
    dictionaryx(x,n)    # this deletes x[0]
    dictionaryx(x,n)    # this causes the error