Convert a python dict to a string and back

后端 未结 10 1598
清酒与你
清酒与你 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 11:07

    Why not to use Python 3's inbuilt ast library's function literal_eval. It is better to use literal_eval instead of eval

    import ast
    str_of_dict = "{'key1': 'key1value', 'key2': 'key2value'}"
    ast.literal_eval(str_of_dict)
    

    will give output as actual Dictionary

    {'key1': 'key1value', 'key2': 'key2value'}
    

    And If you are asking to convert a Dictionary to a String then, How about using str() method of Python.

    Suppose the dictionary is :

    my_dict = {'key1': 'key1value', 'key2': 'key2value'}
    

    And this will be done like this :

    str(my_dict)
    

    Will Print :

    "{'key1': 'key1value', 'key2': 'key2value'}"
    

    This is the easy as you like.

    0 讨论(0)
  • 2020-11-27 11:07

    Convert dictionary into JSON (string)

    import json 
    
    mydict = { "name" : "Don", 
              "surname" : "Mandol", 
              "age" : 43} 
    
    result = json.dumps(mydict)
    
    print(result[0:20])
    

    will get you:

    {"name": "Don", "sur

    Convert string into dictionary

    back_to_mydict = json.loads(result) 
    
    0 讨论(0)
  • 2020-11-27 11:07

    I use yaml for that if needs to be readable (neither JSON nor XML are that IMHO), or if reading is not necessary I use pickle.

    Write

    from pickle import dumps, loads
    x = dict(a=1, b=2)
    y = dict(c = x, z=3)
    res = dumps(y)
    open('/var/tmp/dump.txt', 'w').write(res)
    

    Read back

    from pickle import dumps, loads
    rev = loads(open('/var/tmp/dump.txt').read())
    print rev
    
    0 讨论(0)
  • 2020-11-27 11:12

    The json module is a good solution here. It has the advantages over pickle that it only produces plain text output, and is cross-platform and cross-version.

    import json
    json.dumps(dict)
    
    0 讨论(0)
提交回复
热议问题