2

堆栈溢出中的这个问题回答了如何使用 pymysql 从表中获取字典。但是,此方法将列标题作为键输出,将其值作为该列中的数据输出。

将实际数据作为键和值的最佳方法是什么?

例如:

 Name    |Age
 -------------
 John    |25
 Tom     |45
 Tammy   |18

我想

  {John:25, Tom:45, Tammy:18}

不是

 [{Name:John},{Age:25},....]

这就是我现在所拥有的:

def name2dict(name_list):
    name_list_tuple = tuple(name_list)
    conn = pymysql.connect()
    cur = conn.cursor(pymysql.cursors.DictCursor)
    Name2pos = """SELECT Tables.ID, Tables.Position FROM Tables where Tables.Name in %s"""
    cur.execute(Name2pos, [name_list_tuple])
    query_dict = cur.fetchall()
    cur.close()
    conn.close()
    return query_dict
4

2 回答 2

4

Don't use a dictionary cursor - instead use the normal one. A simple example slightly adapting your code (assuming it runs okay as can't check), but can certainly be improved:

def name2dict(name_list):
    name_list_tuple = tuple(name_list)
    conn = pymysql.connect()
    cur = conn.cursor()
    Name2pos = """SELECT Tables.ID, Tables.Position FROM Tables where Tables.Name in %s"""
    cur.execute(Name2pos)
    query_dict = dict(cur.fetchall())
    cur.close()
    conn.close()
    return query_dict
于 2014-10-23T15:31:07.980 回答
3

我不清楚您当前数据的结构是什么,所以我想我只会为每个数据写一个单独的答案!

d = {
    "Name": ["John", "Tom", "Tammy"], 
    "Age": [25,45,18]
}
new_d = dict(zip(d["Name"], d["Age"]))
print new_d

rows = [
    {"Name": "John", "Age": 25},
    {"Name": "Tom", "Age": 45},
    {"Name": "Tammy", "Age": 18},
]
new_d = {row["Name"]: row["Age"] for row in rows}
print new_d

data = [
    {"Name": "John"}, 
    {"Age": 25},
    {"Name": "Tom"}, 
    {"Age": 45},
    {"Name": "Tammy"}, 
    {"Age": 18},
]
d = {
    "Name": [item["Name"] for item in data if "Name" in item],
    "Age": [item["Age"] for item in data if "Age" in item],
}
new_d = dict(zip(d["Name"], d["Age"]))
print new_d

无论如何,结果是:

{'John': 25, 'Tammy': 18, 'Tom': 45}
于 2014-10-23T15:28:01.043 回答