![](/img/trans.png)
[英]How to read a full dictionary data type from a text file in python?
[英]Read data from text file into dictionary
使用python,我正在從具有以下示例數據的文本文件中導入數據:
ABB : {'Code': 'adr', 'Volume': 2238117, 'Sector': 'Industrials', 'Market_Cap': 'No Data', 'Industry': 'Industrial Products', 'List_Date': '2001-04-06'},
ABEV : {'Code': 'adr', 'Volume': 19348239, 'Sector': 'Consumer Defensive', 'Market_Cap': 'No Data', 'Industry': 'Beverages - Alcoholic', 'List_Date': '2013-11-11'},
我將其導入具有以下代碼段的字典中:
with open('list_all.csv', mode='r') as infile:
reader = csv.reader(infile)
result = {}
for row in reader:
key = row[0]
result[key] = row[1:]
它確實被導入為字典,但是問題是因為KEY不在“”中,例如"ABB"
或"ABEV"
。 導入后,我的dic如下所示:
"ABB : {'Code': 'adr'": [" 'Volume': 2238117",
" 'Sector': 'Industrials'",
" 'Market_Cap': 'No Data'",
" 'Industry': 'Industrial Products'",
" 'List_Date': '2001-04-06'}",
''],
解決此問題的最佳方法是什么
通過它的外觀,你可以讀取行由行,刪除任何尾隨逗號和分裂的:
和ast.literal_eval
的dict
部分,例如:
import ast
with open('yourfile') as fin:
rows = (line.rstrip('\n,').partition(' : ') for line in fin)
data = {r[0]: ast.literal_eval(r[2]) for r in rows}
給您以下data
:
{'ABB': {'Code': 'adr',
'Volume': 2238117,
'Sector': 'Industrials',
'Market_Cap': 'No Data',
'Industry': 'Industrial Products',
'List_Date': '2001-04-06'},
'ABEV': {'Code': 'adr',
'Volume': 19348239,
'Sector': 'Consumer Defensive',
'Market_Cap': 'No Data',
'Industry': 'Beverages - Alcoholic',
'List_Date': '2013-11-11'}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.