How to get a dictionary of data in column1 as key and column2 as the value?

自闭症网瘾萝莉.ら 提交于 2020-01-05 08:04:36

问题


This question in stack overflow answers how would one get dictionary from tables using pymysql. However, this method outputs column header as keys and its value as data in that column.

Whats the best way to have actual data as keys and values?

For example:

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

I want

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

NOT

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

This is what i have right now:

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

回答1:


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



回答2:


It's not clear to me what the structure of your current data is, so I guess I'll just write a separate answer for each one!

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

In any case, the result is:

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


来源:https://stackoverflow.com/questions/26531142/how-to-get-a-dictionary-of-data-in-column1-as-key-and-column2-as-the-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!