Python在“ del FilmName [NewCinema]”上获取KeyError

时间:2018-12-22 22:18:06

标签: python

我使用对Python的了解编写了一个简单的代码,然后突然出现一个错误,说我错位了'r',在一行中,女巫甚至都没有'r',我很沮丧,我对python还是很陌生,所以我不知道从哪里开始调试或在线搜索,所以我来到了堆栈溢出的地方,希望能找到答案并就诸如此类的调试问题提供一些建议,谢谢< / p>

重新制作步骤:输入“删除”,然后输入“伯恩”

顺便说一句,我也不知道我应该包含的女巫代码...

NewSpace = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
Sold = 0

Cinema = {
    1:125,
    2:150,
    3:200,
    4:100
    }

Film = {
    "Finding Dory" : {"AgeR":3,"Seats":125,"Cinema": 1},
    "Bourne" : {"AgeR":18,"Seats":150,"Cinema": 2},
    "Tarzan" : {"AgeR":13,"Seats":175,"Cinema": 3}, 
    "Ghost Busters" : {"AgeR":13,"Seats":100,"Cinema": 4} 
    }

FilmName = {
    1 : {"Name":"Finding Dory"},
    2 : {"Name":"Bourne"},
    3 : {"Name":"Tarzan"}, 
    4 : {"Name":"Ghost Busters"} 
    }


def Remove():
    X = 1
    while X == 1:     
        Remove = input("What film should be removed? ")
        if Remove in Film:
        X = 0
    else:
        print("Name not regognized, retry:")
return Remove

def Available():
    Wich = input("Wich Movie do you want to check? ")
    X = 1

    while X == 1: 

        if Wich in Film:
            print (Film[Wich]["Seats"])
            Cont = input("Continue or Exit?(c/e) ").strip().lower()
            X = 0

            if Cont == "c":
                continue
                print("\n\n")
            else:
                break

        else:
            print("Name not recognized, retry")


def AllMovies():
    Num = len(FilmName)
    X = 1    
    print("Available movies: ")

    while X <= Num:

        print(FilmName[X]["Name"])
        X = X+1





if len(Cinema) == 0:
    X = 1
    Cin = int(input("Insert total amount of cinemas: ").strip())

    while X <= Cin:
        Seats = int(input("Seats in Cinema {}: ".format(X)).strip())
        Cinema[X] = Seats
        X = X + 1

    X = 1

    while X <= Cin:
        Mov1 = str(input("Name of Movie {}: ".format(X)).strip())
        Age1 = int(input("Age rating: ").strip())
        Cinema1 = int(input("Wich cinema: ").strip())
        Film[Mov1] = {"AgeR":Age1,"Seats": Cinema[Cinema1], "Cinema": Cinema1}
        FilmName[Cinema1] = {"Name" : Mov1}
        print(NewSpace)
        X = X + 1







while True:
    AllMovies()
    Movie = input("What Movie would you like to see? ").strip().title()

    if Movie in Film:
        Age = int(input("How old are you? ").strip())

        if Age >= Film[Movie]["AgeR"]:
            if Film[Movie]["Seats"] > 0:
                Film[Movie]["Seats"] = Film[Movie]["Seats"]-1
                Sold = Sold + 1
                print("Enjoy your movie: {}, at cinema {}".format(Movie, Film[Movie]["Cinema"]))
                break
        else:
            print(NewSpace)
            print("You are too young, choose another film")
            print("\n\n")

    elif Movie == "E":
        break

    elif Movie == "Remove":
         Remove = Remove()
         NewCinema = Remove[3]
         print(Remove[3])
         del Film[Remove]
         del FilmName[NewCinema]
         Mov1 = str(input("Name of new movie: ").strip())
         Age1 = int(input("Age rating: ").strip())
         Film[Mov1] = {"AgeR":Age1,"Seats": Cinema[NewCinema], "Cinema": Cinema1}
         FilmName[NewCinema] = {"Name" : Mov1}

    elif Movie == "Available":
        Available()

    elif Movie == "Sales":
        print("You have sold {} tickets".format(Sold))
        print("\n\n\n")

    else:
        print(NewSpace)
        print("We don't have that film... Pick another one")
        print("\n\n")

runfile('C:/Users/Administrator/Desktop/PythonBible/cinima.py',wdir ='C:/ Users / Administrator / Desktop / PythonBible') 可用电影: 海底总动员2 伯恩 泰山 幽灵克星

您想看什么电影?删除

应该去除什么胶卷?伯恩

Traceback (most recent call last):

  File "<ipython-input-1-5a7fa0b19f3b>", line 1, in <module>
    runfile('C:/Users/Administrator/Desktop/PythonBible/cinima.py', wdir='C:/Users/Administrator/Desktop/PythonBible')

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 668, in runfile
    execfile(filename, namespace)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/Administrator/Desktop/PythonBible/cinima.py", line 123, in <module>
    del FilmName[NewCinema]

KeyError: 'r'

1 个答案:

答案 0 :(得分:1)

该错误是描述性的。您正在呼叫del FilmName[NewCinema],而NewCinema只是'r'-您的词典中没有在'r'键下的电影-因此:KeyError

使用print()语句在错误发生的位置之前/附近打印并检查变量。更好的是:学习如何调试:https://wiki.python.org/moin/PythonDebuggingTools

现在您应该更改行

elif Movie == "Remove":
     Remove = Remove()
     NewCinema = Remove   # [3]  is wrong - you set NewCinima to one character
     print(Remove[3])
     del Film[Remove]
     del FilmName[NewCinema]

现在,您需要弄清楚FilmName词典中的键是如何调用的-因为在此使用整数。

您可能应该考虑整个“数据存储”设计-您已经将FilmName的{​​{1}}放入key字典中,因此无需将名称存储在另一个字典中Film下方的dict键,其中另一个integer包含一个dict键,其中包含影片名称...