1

I have a string as below

"{"V":1,"Batch":10001,"File":"abc.csv","ContactorID":"A001"}"

How can I actually convert this string to a dictionary? The string originate from a txt file

Cheang Wai Bin
  • 133
  • 1
  • 7
  • 3
    [`json.loads`](https://docs.python.org/3/library/json.html?highlight=json%20loads#json.loads) – Nick Jul 03 '20 at 01:15
  • 1
    [`ast.literal_eval(..)`](https://docs.python.org/3/library/ast.html#ast.literal_eval) will also work. Just depends what you're doing. This is useful if you have a column of dict strings in a dataframe. – Trenton McKinney Jul 03 '20 at 01:20

1 Answers1

2

You should use the json module. You can either open the file and use json.load(file) or include the text as a string in your program and do json.loads(text). For example:

import json

with open('file.txt', 'r') as file:
    dict_from_file = json.load(file)

or

import json

text = '{"V":1,"Batch":10001,"File":"abc.csv","ContactorID":"A001"}'

dict_from_text = json.loads(text)

For more info see https://realpython.com/python-json/.

Thaddaeus Markle
  • 434
  • 1
  • 4
  • 12