【问题标题】:KeyError in Python 3.4Python 3.4 中的 KeyError
【发布时间】:2014-05-10 20:08:13
【问题描述】:

我在 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'

我做错了什么?

【问题讨论】:

    标签: python dictionary keyerror


    【解决方案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')
    

    【讨论】:

      【解决方案2】:

      “Capcom”不是字典中的键。它是键的值('Street Fighter IV','Resident Evil 4')。所以 video_game_company['Capcom'] 导致 keyError(显然... .因为没有这样的键'Capcom')。

      【讨论】:

        【解决方案3】:

        “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')
        

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-22
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 1970-01-01
        • 2015-04-12
        • 2018-10-10
        相关资源
        最近更新 更多