读取字典列表时出错

2024-06-28 18:53:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下字典清单:

  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"
  }
 ]

当我打印创建的时间时,它工作得很好:

^{pr2}$

我为创建的id值得到正确的输出。但是当我试图读取消息值时,我得到了键错误:“message”。在


Tags: id消息message字典time错误时间created
2条回答

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

您可以更轻松地进行如下调试:

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

这将为您提供一个没有message的{}的整个实例。在

如果您知道数据中所有可能的键,并且不想使用try...except,那么可以检查该键是否存在。在

另一个变体是在所有if语句的else部分将键打印为空,这样您就可以知道有多少数据集对于预期的键没有任何值。在

mydata = [
  {
     "created_time": "2017-07-22T19:54:03+0000",
     "message": "AAAAAAA",
     "id": "1892434161030557_1945301442410495"
  },
  {
     "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"
  }
 ]

for x in mydata:
    if ('created_time' in x):
        print("created_time : " + x['created_time'])
    if ('message' in x):
        print("message      : "+ x['message'])
    if ('id' in x):
        print("id           : " + x['id'])
    print("\n")

样品运行

^{pr2}$

相关问题 更多 >