【问题标题】:Python - KeyError while creating an indexPython - 创建索引时出现 KeyError
【发布时间】:2013-03-13 21:55:24
【问题描述】:

这是代码(它在类中运行):

if profile['profile_picture']:
    profile['profile_picture_raw_path'], # Line 26
    profile['profile_picture_thumbnail'],
    profile['profile_picture'] = self.picture_path(profile['profile_picture'])

密钥不存在。 picture_path 返回的典型结果是

('//domain.com/218971848/21924823397471f5e4e41a803da17f7c.jpg:large', '//domain.com/profile-images/218971848/21924823397471f5e4e41a803da17f7c.jpg:thumb-100', '//domain.com/profile-images/218971848/21924823397471f5e4e41a803da17f7c.jpg:exact')

如您所见,结果是一个包含 3 个元素的元组。

我得到一个错误:

 File "/srv/rwt/production/application/rwt/profile.py", line 26, in load_profile
    profile['profile_picture_raw_path'],
KeyError: 'profile_picture_raw_path'

为什么会出现这个错误?在 Stack Overflow 上搜索了类似的问题,但他们似乎被问及如何通过不存在的键访问字典值。

【问题讨论】:

    标签: python associative-array keyerror


    【解决方案1】:

    profile['profile_picture_raw_path'], 单独一行会被解析为一个独立的表达式(不过,这是一个相当无用的表达式)。

    您需要告诉 Python 解释器下一行是表达式的一部分:

    profile['profile_picture_raw_path'], \
    profile['profile_picture_thumbnail'], \
    profile['profile_picture'] = self.picture_path(profile['profile_picture'])
    

    【讨论】:

    • 顺便提一下:你也可以像(profile['xxx'],profile['yyy'],profile['zzz'])=...这样在作业的左边加上括号
    【解决方案2】:

    使用括号

    if profile['profile_picture']:
        (profile['profile_picture_raw_path'], # Line 26
        profile['profile_picture_thumbnail'],
        profile['profile_picture']) = self.picture_path(profile['profile_picture'])
    

    【讨论】:

      猜你喜欢
      • 2019-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      相关资源
      最近更新 更多