-1

I have some text files with a format like this

{"key":"value", "key":"value", "key":"value"}

{"key":"value", "key":"value", "key":"value"}

There's a new line character after every string. Basically it has multiple dictionaries and I want to read some specific values from them one by one.

Tahir Raza
  • 726
  • 1
  • 7
  • 20
  • 1
    OK, so what have you tried and what's the problem with it? SO is neither a code-writing nor tutorial service. – jonrsharpe Apr 20 '16 at 21:07
  • 1
    Looks like a duplicate. Here is the answer. http://stackoverflow.com/a/4917044/2930045 – RattleyCooper Apr 20 '16 at 21:07
  • @DuckPuncher That's for a JSON file, the question is about a regular file. See http://stackoverflow.com/questions/4803999/python-file-to-dictionary for that. – kirkpatt Apr 20 '16 at 21:10

1 Answers1

0

you can use ast.literal_eval

with open("your_file.txt") as f:
    for line in f:
        my_dict = ast.literal_eval(line.strip())
        # play wiht you dict here now

Demo:

>>> mystr = '{"a":1, "b":2}\n'
>>> k = ast.literal_eval(mystr.strip())
>>> k
{'a': 1, 'b': 2}
>>> type(k)
<type 'dict'>
>>> k['a']
1
Hackaholic
  • 19,069
  • 5
  • 54
  • 72