-1

我用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 Creed", 'Watch Dogs'): 'Ubisoft'}

指标如下:

  1. 育碧
  2. 卡普空
  3. 顽皮狗

但是当我输入:

print("%s" % video_game_company["Capcom"])

我收到以下错误:

KeyError: 'Capcom'

我究竟做错了什么?

4

3 回答 3

1

"Capcom" is not a key in the dictionary.It's a value for the key ('Street Fighter IV', 'Resident Evil 4').So video_game_company['Capcom'] results in a keyError(Obviously....since there is no such key 'Capcom').

于 2014-05-11T11:17:48.810 回答
1

__getitem__在字典上获取键'Capcom'等是值 - 因此是错误。

您应该切换每个键和值以获得所需的行为:

{'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')
于 2014-05-10T20:09:44.060 回答
0

“Capcom”、“Ubisoft”和“Naughty Dog”是字典的值而不是键。

print("%s" % video_game_company[('Street Fighter IV', 'Resident Evil 4')])  
# display Capcom

您需要反转 dict 中的键和值才能执行此操作video_game_company["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')
于 2014-05-10T20:10:13.700 回答