0

My python program reads a pre-defined dictionary to get certain values for processing. I need to be able to change the values of the dictionary. But, as program will be converted to executable file, it should not be defined inside the program.

I was thinking like defining it in a text file. I don't want to write extra code to parse and populate dictionary. I need to know if there is any way to define a dict in a text file and assigning its content directly to python dict.

Like this:

In the text file:

{'a':1,'b':2,'c':3}

NB: The actual one is bit more enrich with values. This is just an example.

In the program: dict_variable = f.read()

So if you print the variable it will be a dictionary object:

{'a':1,'b':2,'c':3}

and can be accessed like dict_variable['a'].

Is there any way to do this?

Leon
  • 31,443
  • 4
  • 72
  • 97
athultuttu
  • 192
  • 3
  • 15
  • Looks like serialization, look at pickle. – polku Jun 28 '16 at 09:41
  • 1
    JSON would be a better fit, as it is readable/modifiable by humans. Note though that the example is invalid syntax; it uses list notation but contains keys/values. – Daniel Roseman Jun 28 '16 at 09:42
  • Should I make this complicated. I just want the user to be able to update values as he will not be familiar with python code and I will be giving an executable which cannot be updated.:( I have corrected syntax:) – athultuttu Jun 28 '16 at 09:47
  • I would use JSON in this context. – salmanwahed Jun 28 '16 at 09:49

1 Answers1

1

You can use eval() :

s = f.read()

d = eval(s)

From Convert a String representation of a Dictionary to a dictionary?

Community
  • 1
  • 1
Stéphane
  • 425
  • 2
  • 7
  • 21