-5

I tried to remove the first and last quote follow string[1:-1]. But it didn't work correctly! Here is my code:

def write_data_to_file(file_name, data):
    f = open(file_name,'wb')
    data_convert_str = dict()
    data_remove_quotes =dict()
    for index_line in range(1, number_lines +1)
       data_convert_str[index_line] = repr(data_line])
       data_remove_quotes[index_line] = data_convert_str[1:-1]
       json.dump(data_remove_quotes[index_line], f)
       f.write('\n')
    f.close()

My data is a dict type: {'a' : 0.001, 'b' : 0.002} that produce in my program.

And the result is: 'a' : 0.001, 'b' : 0.002.

Please explain for me.

Thanks so much for help!

isedev
  • 18,848
  • 3
  • 60
  • 59
PhuongHoang
  • 481
  • 1
  • 4
  • 5

1 Answers1

0

What you are trying to do seems to be turning a string that looks like a dict into a dict.

Removing the quotes won't work, for reasons mentioned by jonrsharpe. Now, the topic of turning a string that looks like a dictionnary into a dictionnary has already been explored on Stack Overflow. Like Here.

Long story short? Use :import ast to import the abstract syntax trees module(works from 2.6 onwards) and then ast.literal_eval(n) with n being the variable that stores you dict as a string, in this case "{'a' : 0.001, 'b' : 0.002}".

Took me five seconds of searching stack overflow to find this, too.

edit : I tested it with your string under 2.7, and it returns the dict you're looking for.

Community
  • 1
  • 1
inirlan
  • 18
  • 1
  • 8
  • `ast.literal_eval(n)` will give you a dict, if you want to use it, assign it to a variable, as simple as that. Although, if you want to write something in a text file(can't tell from that code), you might as well write the string into it and turn the values you retrieve through the AST before use. Don't forget to accept the answer if you found it helpful. – inirlan Sep 30 '14 at 07:34
  • Don't forget to accept the answer(the little check sign next to the answer)! ;) – inirlan Oct 07 '14 at 13:49