Reputation: 673
I have a dictionary stored inside a text file called 'Dict.txt' like so:
[{1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 15: 0}]
I've got some code to take this file, and turn it into a dictionary:
import json, ast
file = open('Dict.txt', 'r')
save = file.read()
file.close()
for func in (ast.literal_eval, json.loads):
file = func(save)
file = file[0]
But when I run the code, I get the error:
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
I'm not used to working with dictionaries, json, or ast. So I do know why this is happening, help would be appreciated.
Upvotes: 0
Views: 100
Reputation: 1034
Regular Expression is your best friend :)
import re
import ast
file = open('dict.txt', 'r')
save = file.read()
file.close()
result = re.search('\[(.*)\]',save)
my_dict = result.group(1)
print my_dict
my_dict = ast.literal_eval(my_dict)
print type(my_dict)
print my_dict
Upvotes: 1
Reputation: 7529
That's not valid JSON because the outermost structure is a list, not a dict and the keys are numbers rather than strings. You can still use literal_eval like this:
file = open('Dict.txt', 'r')
your_list_with_a_dict = ast.literal_eval(file.read())
your_dict = your_list_with_a_dict[0]
file.close()
Upvotes: 1
Reputation: 26578
You can just use literal_eval
when you read the data from your file. So, you can simply do this:
Content of test.txt
:
[{1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 15: 0}]
Code reading the file and outputting in desired data-structure:
from ast import literal_eval
data = []
with open('test.txt') as a:
data = literal_eval(a.read())
print(data)
Output:
[{1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 15: 0}]
Upvotes: 1