这个问题在堆栈溢出回答如何将一个收到使用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
不要使用字典光标 - 改用正常的。 一个简单的例子稍微调整你的代码(假设它运行没关系,不能检查),但肯定可以改进:
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
这不是我清楚你当前的数据结构是什么,所以我想我就写为每一个单独的答案!
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}
文章来源: How to get a dictionary of data in column1 as key and column2 as the value?