Convert a python dict to a string and back

后端 未结 10 1653
清酒与你
清酒与你 2020-11-27 10:17

I am writing a program that stores data in a dictionary object, but this data needs to be saved at some point during the program execution and loaded back into the dictionar

10条回答
  •  青春惊慌失措
    2020-11-27 10:47

    If your dictionary isn't too big maybe str + eval can do the work:

    dict1 = {'one':1, 'two':2, 'three': {'three.1': 3.1, 'three.2': 3.2 }}
    str1 = str(dict1)
    
    dict2 = eval(str1)
    
    print dict1==dict2
    

    You can use ast.literal_eval instead of eval for additional security if the source is untrusted.

提交回复
热议问题