6

I have the following file dic.txt:

{'a':0, 'b':0, 'c':0, 'd':0}

I want to read its contents and use as a dictionary. After entering new data values I need to write them into that file. Basically I need a script to work with the dictionary, update its values and save them for later use.

I have a working script, but can't figure out how to actually read the contents of the dic.txt into a variable in the script. Cause when I try this:

file = '/home/me/dic.txt'
dic_list = open(file, 'r')
mydic = dic_list
dic_list.close()

What I get as mydic is a str. And I can't manipulate its values. So here is the question. How do I create a dictionary from a dic.txt?

minerals
  • 1,195
  • 4
  • 15
  • 22
  • Does the text file contain a string representation of a Python dictionary or JSON? Edit: `'`s are not valid JSON, so question answered. – Gareth Latty Dec 10 '12 at 21:37
  • Is there any reason why you aren't using [pickle](http://docs.python.org/2/library/pickle.html) to serialize stuff? – NullUserException Dec 10 '12 at 21:40
  • 1
    Does this help? Seems pretty straight forward. http://stackoverflow.com/questions/988228/converting-a-string-to-dictionary – JMT2080AD Dec 10 '12 at 21:40
  • @NullUserException Human readability can be valuable. That said, it would be better to use a well standardized format like JSON. – Gareth Latty Dec 10 '12 at 21:40
  • @Lattyware When I pickle and unpickle something I can expect that object to be the same. Can't say the same thing about JSON. – NullUserException Dec 10 '12 at 21:48
  • 1
    @NullUserException I don't see where the asker implies that is valuable to them. There is a place for both, and there is no reason to believe that `pickle` is more suitable here. – Gareth Latty Dec 10 '12 at 21:51
  • thanks, had to read what JSON actually is :) – minerals Dec 10 '12 at 21:54

3 Answers3

13

You need to parse the data to get a data structure from a string, fortunately, Python provides a function for safely parsing Python data structures: ast.literal_eval(). E.g:

import ast

...

with open("/path/to/file", "r") as data:
    dictionary = ast.literal_eval(data.read())
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
4

You can use the python built-in function eval():

   >>> mydic= "{'a':0, 'b':0, 'c':0, 'd':0}"
    >>> eval(mydic)
    {'a': 0, 'c': 0, 'b': 0, 'd': 0}
    >>> 
Dinesh
  • 41
  • 2
-1
>>> import json
>>> json.loads('{"a":0, "b":0, "c":0, "d":0}')
{u'a': 0, u'c': 0, u'b': 0, u'd': 0}

So

with open('/path/to/file', 'r') as f:
    d = json.loads(f.read().replace("'", '"')
Alexey Kachayev
  • 6,106
  • 27
  • 24