-2

I created a file and there is a dictionary. Now I want that dictionary from the file but I do not want in string and I don't want the newline character. I obtained something like this:

"{'Greennhouse 1': {'Product': '4', 'Location of greenhouse': '2',
'Unities of the product': 6, 'Designation': '1', 'Growth state of the
product': '5', 'Code of wsn': 1, 'Area of greenhouse': 3}}\n"

But I want this:

{'Greennhouse 1': {'Product': '4', 'Location of greenhouse': '2',
'Unities of the product': 6, 'Designation': '1', 'Growth state of the
product': '5', 'Code of wsn': 1, 'Area of greenhouse': 3}}
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241

3 Answers3

4

The ast.literal_eval function is designed to convert Python literal expressions represented as a string, into actual Python data structures. So:

import ast

dictionary = ast.literal_eval(string)

The presence of the \n newline character in the input will be of no consequence.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • I use that and it worked. But now I can't get values from the dictionary... What should I do? I already try by creating a new dictionary, using the get(), but nothing works... – Diana Vasconcelos Ferreira Apr 29 '15 at 22:55
  • @DianaVasconcelosFerreira: It's unclear what you mean by "it worked" and then you say that you can't get values from the dictionary. If you continue to have trouble, I suggest opening a new question for the next problem you encounter. – Greg Hewgill Apr 30 '15 at 02:45
0

although better ast.literal_eval use, depending on the circumstances may be used exec, who interprete all code into a string

s = "{'Greennhouse 1': {'Product': '4', 'Location of greenhouse': '2', 'Unities of the product': 6, 'Designation': '1', 'Growth state of the product': '5', 'Code of wsn': 1, 'Area of greenhouse': 3}}\n"
s = "d=" + s
exec s
print d
Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62
0

to get your dictionnary from a file as the way you want you have to save it like an object you can use pickle from python standard library

import pickle
mydic = {'Greennhouse 1': {'Product': '4', 'Location of greenhouse': '2',
       'Unities of the product': 6, 'Designation': '1', 'Growth state of the
        product': '5', 'Code of wsn': 1, 'Area of greenhouse': 3}}
with open("mydic.dic","wb") as f :
    pickle.dump(mydic,f)
# later in code
with open("mydic.dic","rb") as f :
    mynewdic = pickle.load(f)
    print mynewdic
rawinput
  • 132
  • 1
  • 7