KeyError上的字典定​​时del运算符?

时间:2015-10-16 21:25:29

标签: python dictionary timer timeit del

我一直在为我正在学习的课程进行python作业,而我却无法弄清楚如何通过这个KeyError。我正在尝试在python中对字典中使用del运算符,这是我的代码:

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))

每次我尝试运行此代码时都会出现以下错误

  

追踪(最近一次通话):     文件“/Users/mcastro/PycharmProjects/untitled1/testdel.py”,第21行,在       dict_secs = timeDict.repeat(5,5)     文件“/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/timeit.py”,第206行,重复       t = self.timeit(数字)     文件“/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/timeit.py”,第178行,在timeit       timing = self.inner(it,self.timer)     文件“”,第6行,在内部     在dictionaryx中输入文件“/Users/mcastro/PycharmProjects/untitled1/testdel.py”,第10行       del x [0]   KeyError:0

我无法弄清楚为什么我会收到此错误或如何解决此问题,据我所知,错误引用的密钥存在但无法删除?任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

您的timeit循环每次都使用相同的字典x。第一次调用dictionaryx(x,n)时,它会删除元素0,以便下次调用它时不存在。

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