从运行时指定的列动态构建字典

时间:2019-06-03 22:05:44

标签: python python-3.x pyodbc

有人告诉我我需要使用映射表而不是我制作的硬编码字典。必须有一个比下面的代码更好的方法才能将3列的表放入字典中?

映射表

AgentGrp, Property, TimeZone  #Headers
HollyWoodAgent  Sunset  PST
UnionSquareAgent UnionSquare PST

转到以下词典:

{'HollyWoodAgent': ['Sunset', 'PST'], 'UnionSquareAgent': ['UnionSquare', 'PST']}

代码:

import pandas as pd
import pyodbc
import datetime
import sys
import csv

VipAgent = "{"

finalSql = "SELECT  agentgrp, property, timezone FROM sandbox_dev.agentgrp_map;"

colcnt = 0

try:

    conn = pyodbc.connect("DSN=Dev")

    cursor = conn.cursor()
    cursor.execute(finalSql)
    for row in cursor.fetchall():
        VipAgent += "'" + row.prop + "VipAgent':['" + row.prop + "','" + row.tz + "'],"
        colcnt = colcnt + 1
        if(colcnt==3):
            VipAgent = VipAgent + "\n"
            colcnt = 0

except my.Error as e:
    print(e)

VipAgent = VipAgent[:-1] + "}"

Dict = eval(VipAgent)

print(Dict)

我确实得到了预期的值。必须有更好的python出路。

1 个答案:

答案 0 :(得分:0)

假设您将文件中的“映射表”读入与此类似的Python列表中,我们将以此为前提

item_map = ['AgentGrp', 'Property', 'TimeZone']

执行了SELECT查询后

cursor.execute(finalSql)

然后您可以像这样构建dict

result_dict = {}
while (True):
    row = cursor.fetchone()
    if (row):
        result_dict[row.__getattribute__(item_map[0])] = \
                [row.__getattribute__(x) for x in item_map[1:]]
    else:
        break
print(result_dict)
# {'HollyWoodAgent': ['Sunset', 'PST'], 'UnionSquareAgent': ['UnionSquare', 'PST']}

诀窍是使用row.__getattribute__(例如row.__getattribute__('column_name'))而不是对row.column_name进行硬编码。