简体   繁体   中英

How to convert a text file content to dictionary

I wrote a dictionary value to a text file. Now I want to read the same text file to extract the content as a dictionary with Keys and values.

The text file content is in this format

   '5945-01-311-3597': {'NSN': '5945-01-311-3597', 'Nomenclature': 'ARMATURE, ELECTROMAG', 'RFQ_Date': '2-13-2019', 'RFQ_QTY': ' 25', 'Time': '2019-08-14 20:17:56', 'Add_method': 'Dibbs Extract'}, '3110-00-365-4766': {'NSN': '3110-00-365-4766', 'Nomenclature': 'BEARING, BALL, ANNULA', 'RFQ_Date': '2-13-2019', 'RFQ_QTY': ' 29', 'Time': '2019-08-14 20:17:56', 'Add_method': 'Dibbs Extract'}, '3120-01-584-4379': {'NSN': '3120-01-584-4379', 'Nomenclature': 'BEARING, WASHER, THRU', 'RFQ_Date': '2-13-2019', 'RFQ_QTY': ' 1', 'Time': '2019-08-14 20:17:56', 'Add_method': 'Dibbs Extract'},

so one key value pair will look like this

  '5945-01-311-3597': {'NSN': '5945-01-311-3597', 'Nomenclature': 'ARMATURE, ELECTROMAG', 'RFQ_Date': '2-13-2019', 'RFQ_QTY': ' 25', 'Time': '2019-08-14 20:17:56', 'Add_method': 'Dibbs Extract'} 

with 5945-01-311-3597 being the key here and everything else in brack being the values.

 RFQ_file=open("RFQs/8-14-2019-rfq.txt", "r")

 RFQ_file_content =RFQ_file.read()

 rfqDict = RFQ_file_content.split('},')

the above code produces this output

'5945-01-311-3597': {'NSN': '5945-01-311-3597', 'Nomenclature': 'ARMATURE, ELECTROMAG', 'RFQ_Date': '2-13-2019', 'RFQ_QTY': ' 25', 'Time': '2019-08-14 20:17:56', 'Add_method': 'Dibbs Extract'

what is the best way to convert the text file content above to a dictionary so that I can get the values for a specific key ?

You can use json package to convert string to dict .

For example,

import json

with open(PATH_TO_YOUR_DATA, 'r') as f:
    data = json.load(f)

Then you can get the value you want from dict data .

Note you may have trailing comma in the file which may fail the JSON loading.

Try:

import json

# read data
with open('data.txt', 'r') as file:
    data = file.read()

data = data.strip().rstrip(',')  # remove potential blank lines and trailing comma

your_dict = json.loads(data)

When you are saving the file, try using json.dumps(your_dict) to avoid these issues.

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