Skip to main content
 首页 » 编程设计

python之读取字典列表时出现KeyError

2025年05月04日25bjzhanghao

我有以下字典列表:

  mydata = [ 
  { 
     "created_time": "2017-07-22T19:54:03+0000", 
     "message": "AAAAAAA", 
     "id": "1892434161030557_1945301442410495" 
  }, 
  { 
     "created_time": "2017-07-16T12:55:37+0000", 
     "message": "YYYYYYYYY", 
     "id": "1892434161030557_1941921866081786" 
  }, 
  { 
     "created_time": "2017-07-16T12:43:44+0000", 
     "message": "PPPPPPPPPPPPP", 
     "id": "1892434161030557_1941917586082214" 
  }, 
  { 
     "created_time": "2017-05-12T05:42:58+0000", 
     "message": "m", 
     "id": "1892434161030557_1906744326266207" 
  } 
 ] 

当我打印 created_time 时它工作正常:

for x in mydata: 
    print(x['created_time']) 

我得到了 created_time 和 id 值的正确输出。但是当我尝试读取 message 值时,我得到了 KeyError: 'message'。

请您参考如下方法:

鉴于您的示例数据,这个简单的操作应该可以正常工作。我想 message 在某些情况下不存在。

您可以像这样更轻松地进行调试:

for x in mydata: 
    try: 
        msg = x['message'] 
    except KeyError: 
        raise ValueError('No "message" key in "%s"' % (x, )) 
    print(msg) 

这将为您提供没有message 的x 的整个实例。