繁体   English   中英

从 pandas.read_sql_query().to_dict() 获取下一个键并用于字典理解

[英]Getting the next key from pandas.read_sql_query().to_dict() and use in dictionary comprehension

我从数据库中提取两列后得到的数据结构来自:

sql = pd.read_sql_query("select Name,FieldType from database.dbo.meta_table where [Table] = 'CLoad'",conn)

返回这个:

 {'Name': {0: 'Item0', 1: 'Item1', 2: 'Item2', 3: 'Item3', 4: 'Item4', 5: 'Item5', 6: 'Item6', 7: 'Item7', 8: 'Item8', 9: 'Item9', 10: 'Item10', 11: 'Item11', 12: 'Item12'}, 'FieldType': {0: 'int', 1: 'int', 2: 'int', 3: 'int', 4: 'date', 5: 'date', 6: 'datetime', 7: 'int', 8: 'bit', 9: 'bit', 10: 'datetime2', 11: 'varchar', 12: 'bit'}}

我的问题是使用 output 从中创建一个字典,例如:

{'Item0': 'int', 'Item1': 'int', 'Item2': 'int', 'Item3': 'int', 'Item4': 'date', 'Item5': 'date', 'Item6': 'datetime', 'Item7': 'int', 'Item8': 'bit', 'Item9': 'bit', 'Item10': 'datetime2', 'Item11': 'varchar', 'Item12': 'bit'}

我确实通过像这样对密钥进行硬编码来解决问题:

e = {sql['Name'][i]:sql['FieldType'][i] for i in range(len(sql[key]))}

但是必须有一种方法来以编程方式按顺序获取下一个键。 任何有关更好解决方案的帮助将不胜感激。

sql转换为dataframe然后使用df.to_dict

sql =  {'Name': {0: 'Item0', 1: 'Item1', 2: 'Item2', 3: 'Item3', 4: 'Item4', 5: 'Item5', 6: 'Item6', 7: 'Item7', 8: 'Item8', 9: 'Item9', 10: 'Item10', 11: 'Item11', 12: 'Item12'}, 'FieldType': {0: 'int', 1: 'int', 2: 'int', 3: 'int', 4: 'date', 5: 'date', 6: 'datetime', 7: 'int', 8: 'bit', 9: 'bit', 10: 'datetime2', 11: 'varchar', 12: 'bit'}}

output_dict = pd.DataFrame(sql).set_index('Name').to_dict()['FieldType'] 

Output:

{'Item0': 'int',
 'Item1': 'int',
 'Item2': 'int',
 'Item3': 'int',
 'Item4': 'date',
 'Item5': 'date',
 'Item6': 'datetime',
 'Item7': 'int',
 'Item8': 'bit',
 'Item9': 'bit',
 'Item10': 'datetime2',
 'Item11': 'varchar',
 'Item12': 'bit'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM