Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用while循环字典迭代时出现keyError_Python_Dictionary_While Loop - Fatal编程技术网

Python 使用while循环字典迭代时出现keyError

Python 使用while循环字典迭代时出现keyError,python,dictionary,while-loop,Python,Dictionary,While Loop,我试图迭代两个输入,然后填充字典,但每次在最后一个键时我都会得到这个键错误,当我输入最后一个键时,它会抛出这个错误 # Get user input and define our roster roaster = {} while True: position = input('position: ') player = input('player: ') roaster[position] = [player] roaster.update() if

我试图迭代两个输入,然后填充字典,但每次在最后一个键时我都会得到这个键错误,当我输入最后一个键时,它会抛出这个错误

 # Get user input and define our roster
roaster = {}
while True:
    position = input('position: ')
    player = input('player: ')
    roaster[position] = [player]
    roaster.update()
    if len(roaster) == 1:
        break
print(f'Your starting {len(roaster)} for the upcoming basketball season')

print(f'\t\t{roaster[player]}:\t\t{roaster[position]}')
错误:

Traceback (most recent call last):
File "/home/Basketball_Roaster_App/basketball_ball_roaster.py", line 16, in <module>
print(f'\t\t{roaster[player]}:\t\t{roaster[position]}')
KeyError: 'mike'
回溯(最近一次呼叫最后一次):
文件“/home/Basketball\u Roaster\u App/Basketball\u Roaster.py”,第16行,在
打印(f'\t\t{roaster[player]}:\t\t{roaster[position]}
关键错误:“迈克”

你的
烘焙师
使用位置作为键,而不是玩家。

你的问题是
烘焙师[玩家]

作为播放机,您的las输入是mike,因此dict是
roaster={位置:'mike'}

您只能使用键访问dict,因此需要使用posistion来访问。 Python试图在键中找到“mike”,但找不到它

你应该做的是:

for key in roaster:
    print(roaster[key]: key)
你可以试试这个

烘焙者={位置:玩家}

打印烘焙程序.items()


您提供了什么输入来获得此错误?顺便问一下,花名册的拼写没有“a”这是什么
update
功能?另外,为什么总是只允许一个玩家--
中断
确保了这一点。这是一个非常小的烤炉吗?我在供应细绳