如何将 column1 中的数据字典作为键,将 column2 中的数据作为值? [英] How to get a dictionary of data in column1 as key and column2 as the value?

查看:61
本文介绍了如何将 column1 中的数据字典作为键,将 column2 中的数据作为值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

例如:

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

我想要

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

不是

 [{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

推荐答案

不要使用字典光标 - 而是使用普通光标.一个简单的例子稍微调整你的代码(假设它运行正常,因为无法检查),但肯定可以改进:

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

这篇关于如何将 column1 中的数据字典作为键,将 column2 中的数据作为值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆