Skip to content
Advertisement

How to get a list with dict entries from text file?

I saved a list with dict entries to a txt file.

When I try to read it back into python with

data = open("my_saved_data.txt","r")

I just get a huge string which looks like this:

[{key1:"value",key2:"value"},{key1:"value",key2:"value"},{key1:"value",key2:"value"}]

What’s an easy way to get this back in the original format?

Advertisement

Answer

What you want is “Convert a String to JSON”, but the type of your file content is not JSON, because the key in JSON should be enclosed in double quotes.

The correct content should like this:

[{"key1":"value","key2":"value"},{"key1":"value","key2":"value"},{"key1":"value","key2":"value"}]

then we can convert it to original format:

with open("my_saved_data.txt","r") as f:
    data = f.read()

print(data)
# '[{"key1":"value","key2":"value"},{"key1":"value","key2":"value"},{"key1":"value","key2":"value"}]'

import json
json.loads(data)
#[{'key1': 'value', 'key2': 'value'},
# {'key1': 'value', 'key2': 'value'},
# {'key1': 'value', 'key2': 'value'}]

Please make sure whether your key in str is enclosed or not, if not, we can make it enclosed by:

with open("my_saved_data.txt","r") as f:
    data = f.read()

data.replace('key1','"key1"').replace('key2','"key2"')
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement