读取字典列表时的KeyError

时间:2017-07-22 20:50:08

标签: 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"
  }
 ]

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

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

我获得 created_time id 值的正确输出。但是当我尝试阅读消息值时,我会收到 KeyError:' message'

2 个答案:

答案 0 :(得分:4)

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

你可以更容易地调试这个:

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

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

答案 1 :(得分:1)

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

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

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")

示例运行

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