【问题标题】:Python ValueError: 'dictionary update sequence element #0 has length 4; 2 is required'Python ValueError: '字典更新序列元素#0 的长度为 4; 2 是必需的'
【发布时间】:2017-12-27 22:58:55
【问题描述】:

我创建了一个从数据库中获取数据,将其转换为 json 格式并返回 JSON 响应的方法。

    def getEchoResource(self):
        try:
           row = self.cursor.execute("SELECT * FROM echo_resource_log WHERE DATE(last_update) = CURDATE();")
           if row:
              response = app.response_class(response=json.dumps(dict(self.cursor.fetchall())), status=200, mimetype='application/json')
              return response
        except MySQLdb.Error as e:
           logger.error("Error %d: %s" % (e.args[0],e.args[1]))
        except Exception, e:
           logger.error("Error : ", str(e))

该方法抛出此错误消息 - ValueError: 'dictionary update sequence element #0 has length 4; 2 是必需的'

追踪-

>/app/worker/echo/apps/opsware_flask_rest_app/opsware_flask_rest_app/
 updateEchoResource.py(123)getEchoResource()
-> row = self.cursor.execute("SELECT * FROM echo_resource_log WHERE 
  DATE(last_update) = CURDATE();")
 (Pdb) n
 >/app/worker/echo/apps/opsware_flask_rest_app/opsware_flask_rest_app/
  updateEchoResource.py(124)getEchoResource()
-> if row:
 (Pdb) n
 >/app/worker/echo/apps/opsware_flask_rest_app/opsware_flask_rest_app/
  updateEchoResource.py(125)getEchoResource()
-> response = 
  app.response_class(response=json.dumps(dict(self.cursor.fetchall())), 
  status=200, mimetype='application/json')
 (Pdb) n
  ValueError: 'dictionary update sequence element #0 has length 4; 2 is 
  required'
 >/app/worker/echo/apps/opsware_flask_rest_app/opsware_flask_rest_app/
  updateEchoResource.py(125)getEchoResource()

行返回 -

('n3pvap168', 'X2Linux_NSS', 'Contact does not exist in Contacts table', datetime.datetime(2017, 7, 21, 4, 27, 37))

【问题讨论】:

  • 我们能看到确切的错误轨迹吗?
  • @Wintro 在原始问题中添加了跟踪。
  • 你能从cursor获取一条记录并打印出来给我们看吗?
  • 打印了一行,请检查问题。 @Wintro
  • 你确定这个方法会抛出错误吗?请包含回溯(堆栈跟踪)。

标签: python mysql json


【解决方案1】:

您可能知道,Python 字典是一组无序的键值对。所以字典中的每个条目都必须有一个键和一个值。这里发生的情况是,您正在尝试将四个对象的序列转换为字典,如您的行所示(因此错误预期长度为 2,长度为 4)。

要解决此问题,您需要将 4 长度数据结构转换为 2 长度数据结构。这可以通过创建一个长度为 2 的数组并将要用作键的字符串存储在数组的 0-index 中并将行的其余部分存储在 1-index 中来完成。您也许可以使用切片来实现这一点。

【讨论】:

    猜你喜欢
    • 2021-04-01
    • 1970-01-01
    • 2015-02-22
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 1970-01-01
    相关资源
    最近更新 更多