This question回答如何使用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
答案 0 :(得分:3)
不要使用字典光标 - 而是使用普通光标。一个简单的例子稍微调整你的代码(假设它运行正常,因为无法检查),但肯定可以改进:
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
答案 1 :(得分:2)
我不清楚您当前数据的结构是什么,所以我想我只会为每个数据单独写一个答案!
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}