Python 3.4中的KeyError
我用python制作了一本字典,目前为止,我这样打印它并没有什么问题:Python 3.4中的KeyError,python,dictionary,keyerror,Python,Dictionary,Keyerror,我用python制作了一本字典,目前为止,我这样打印它并没有什么问题: print(video_game_company) 我会得到预期的结果: {('Street Fighter IV', 'Resident Evil 4'): 'Capcom', ('Crash Bandicoot', 'Uncharted', 'The Last of Us'): 'Naughty Dog', ('Prince of Persia: The Forgotten Sands', "Assassin's Cr
print(video_game_company)
我会得到预期的结果:
{('Street Fighter IV', 'Resident Evil 4'): 'Capcom', ('Crash Bandicoot', 'Uncharted', 'The Last of Us'): 'Naughty Dog', ('Prince of Persia: The Forgotten Sands', "Assassin's Creed", 'Watch Dogs'): 'Ubisoft'}
指标如下:
育碧软件
卡普康
顽皮狗
但当我打字时:
print("%s" % video_game_company["Capcom"])
我得到以下错误:
KeyError: 'Capcom'
我做错了什么?\uuu getitem\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
您应该切换每个键和值以获得所需的行为:
{'Ubisoft': ('Prince of Persia: The Forgotten Sands', "Assassin's Creed", 'Watch Dogs'), 'Naughty Dog': ('Crash Bandicoot', 'Uncharted', 'The Last of Us'), 'Capcom': ('Street Fighter IV', 'Resident Evil 4')}
现在它可以正常工作了:
print("%s" % video_game_company["Capcom"])
# ('Street Fighter IV', 'Resident Evil 4')
“Capcom”、“育碧软件”和“淘气狗”是字典中的值,而不是键
print("%s" % video_game_company[('Street Fighter IV', 'Resident Evil 4')])
# display Capcom
您需要反转dict中的键和值,才能在公司[Capcom]中进行视频游戏
Capcom不是字典中的一个键。它是“街头斗士IV”、“生化危机4”键的值。因此,视频游戏公司['Capcom']显然会导致一个键错误……因为没有这样的键“Capcom”。如果它对您有帮助,请不要忘记。
video_game_company = {'Ubisoft': ('Prince of Persia: The Forgotten Sands', "Assassin's Creed", 'Watch Dogs'),
'Naughty Dog': ('Crash Bandicoot', 'Uncharted', 'The Last of Us'),
'Capcom': ('Street Fighter IV', 'Resident Evil 4')}
print("%s" % video_game_company["Capcom"])
# displays ('Street Fighter IV', 'Resident Evil 4')