簡體   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