简体   繁体   中英

Read data from text file into dictionary

using python, I am importing data from a text file with below sample 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'},

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" . once I import it my dic looks like:

"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:

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:

{'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'}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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