【问题标题】:Error when trying to filter a list of dictionaries with a specific value i get error尝试过滤具有特定值的字典列表时出错我收到错误
【发布时间】:2018-07-11 18:25:47
【问题描述】:

我从 mysql 数据库的表中获取数据。 我正在尝试过滤具有特定值的字典列表。当我执行代码时,出现以下错误:

使用 IDE = PyCharm。

错误:

[x.append(k) for k in lst_cmp_helpdesk_dic if "Doble" in k[key]]

TypeError: 'int' 类型的参数不可迭代

import mysql.connector


def test_initialize_test_data():

    global lst_cmp_helpdesk
    global lst_cmp_helpdesk_dic

    cnx = mysql.connector.connect(user='User', password='Password', host='Srv Name or IP', database='DataBase Name')
    try:
        cursor_dic = cnx.cursor(dictionary=True,buffered=True)
        cursor_dic.execute("select * from Table_Name")
        lst_cmp_helpdesk_dic = cursor_dic.fetchall()
    
        x = []
        for key in lst_cmp_helpdesk_dic[0].keys():
            [x.append(k)for k in lst_cmp_helpdesk_dic if "Search_Text" in k[key]]
            count = len(([dict(t) for t in set([tuple(d.items()) for d in x])]))
        print("\n Length = " + str(count))
    finally:
        cnx.close()

【问题讨论】:

  • 相反,k 是一个整数,尝试使用[key] 进行索引是无效的
  • 啊,你是对的 - 这会给出一个not subscriptable 错误

标签: python mysql


【解决方案1】:

你说的是

"Search_Text" in k[key]

k[key] 返回一个 int。因此,您不能使用 in 对其进行迭代。

您可以实际打印出lst_cmp_helpdesk_dic[0].keys() 并确保其中包含您要与"Search_text" 进行比较的名称

【讨论】:

  • 谢谢,我发现返回值是表中项目的 ID。我添加了 str() 函数将所有数据转换为字符串,它解决了我的问题。
  • 没问题。很高兴它有帮助。
【解决方案2】:

我猜是从数据库访问数据的问题。它可能是数据库中的不同数据类型,并且您正在以不同的格式访问。我建议请检查您的数据库一次。

【讨论】:

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