[英]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.