【问题标题】:is there a better or more elegant way to handling dictionary loop exception in python?有没有更好或更优雅的方法来处理python中的字典循环异常?
【发布时间】:2020-01-08 12:34:15
【问题描述】:

基本上我只是在解析一个 JSON 文件,其中包含有关几部电影的信息,并将其中一些保存在不同的字典中以供以后使用

示例: 不是所有的电影都有描述,我正在使用 try/except 来处理 json 中没有描述时出现的“keyError”,有没有更好的方法?

for movie in json:
    # other entries
    try:
        description = {"description": movie_details['Description']}
    except KeyError:
        description = {"description": ""}
    # other entries
    try:
        other_value = {"other_value": movie_details["other_value"]
    except KeyError:
        other_value = {"other_value": ""}

在我看来这很“肮脏”,如果你有一些技巧可以编写更清晰的代码会很棒

谢谢

【问题讨论】:

  • 你可以使用.get,见here
  • 如果movie_detailsdict,您可以在访问'value' in movie_details 之前询问

标签: python python-3.x dictionary exception


【解决方案1】:

一种方法是将movie_details 转换为collections.defaultdict

movie_details = collections.defaultdict(str,movie_details)

如果未找到键,则专用字典对象调用str 来创建新键(空字符串)

完成此操作后,只需像普通的 dict 访问一样使用它:

description = {'description': movie_details['Description']}

【讨论】:

    【解决方案2】:

    一种方法是使用带有标记值的.get()

    for movie in json:
        description = {'description': movie_details.get('Description', '')}
        # and similarly for other values...
    

    这确保如果没有找到键,则使用标记值。

    我不确定您是否需要在循环中使用movie_detailsmovie。我想你的意思是后者。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-07
      • 1970-01-01
      相关资源
      最近更新 更多