[英]Read data from text file into dictionary
using python, I am importing data from a text file with below sample data: 使用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'},
I am importing it into a dictionary with the following snippet: 我将其导入具有以下代码段的字典中:
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:]
it does get imported as a dictionary but the issue is because the KEY is not in "" such as "ABB"
or "ABEV"
. 它确实被导入为字典,但是问题是因为KEY不在“”中,例如
"ABB"
或"ABEV"
。 once I import it my dic looks like: 导入后,我的dic如下所示:
"ABB : {'Code': 'adr'": [" 'Volume': 2238117",
" 'Sector': 'Industrials'",
" 'Market_Cap': 'No Data'",
" 'Industry': 'Industrial Products'",
" 'List_Date': '2001-04-06'}",
''],
what is the best way to try to resolve this problem 解决此问题的最佳方法是什么
By the looks of it, you can read line-by-line, remove any trailing commas and split on the :
and ast.literal_eval
the dict
part, eg: 通过它的外观,你可以读取行由行,删除任何尾随逗号和分裂的
:
和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}
Which give you data
of: 给您以下
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.