KeyError:“Name”,有什么问题?

2024-06-07 05:13:52 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能告诉我为什么我会犯这个错误吗?我认为代码没有问题,当我用Name,Start,End替换**item时,我仍然无法使它工作

print("To finish input enter nothing.")
Schedule = []
Finish = False
while not Finish:
    Name = input("What is the name of the show?: ")
    Start = input("What time does the show start?: ")
    End = input("What time does the show end?: ")
    Schedule.append({'Name':Name, 'Start':Start, 'End':End})
    print("{0:<10}  |  {1:<10}  -  {2:<10}".format(Name,Start,End))
    print("{Name:<10}  |  {Start:<10}  -  {End:<10}  ".format(**item))
    if len(Name) == 0 or len(Start) == 0 or len(End) == 0:
        Finish = True

Tags: thenameformatinputlentimeshowitem
3条回答
print("{Name:<10}  |  {Start:<10}  -  {End:<10}  ".format(**item))

这个代码对我来说很好,除了你没有定义项?

假设该项是某种容器(名称、开始、结束),则需要将此行更改为:

print("{:<10}  |  {:<10}  -  {:<10}  ".format(**item))

这样你就不用键了,它可以按顺序填充字段。 或:

print("{Name:<10}  |  {Start:<10}  -  {End:<10}  ".format(Name=item[0],
                                                          Start=item[1],
                                                          End=item[2]))

如果你真的想用钥匙。

基本上,您的键错误是在没有为键提供值的情况下用键({Name:<;10})请求值。

希望能有所帮助。

你永远不会创建item

item = {'Name':Name, 'Start':Start, 'End':End}
Schedule.append(item)

试试这个:

print("To finish input enter nothing.")
Schedule = []
Finish = False
while not Finish:
    Name = raw_input("What is the name of the show?: ")
    Start = raw_input("What time does the show start?: ")
    End = raw_input("What time does the show end?: ")
    Schedule.append({'Name':Name, 'Start':Start, 'End':End})
    print("{0:<10}  |  {1:<10}  -  {2:<10}".format    (Name,Start,End))
    print("{Name:<10}  |  {Start:<10}  -  {End:<10}  ".format    (**item))
    if len(Name) == 0 or len(Start) == 0 or len(End) == 0:
        Finish = True

相关问题 更多 >