Convert a python dict to a string and back

后端 未结 10 1597
清酒与你
清酒与你 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.

    0 讨论(0)
  • 2020-11-27 10:58

    If in Chinses

    import codecs
    fout = codecs.open("xxx.json", "w", "utf-8")
    dict_to_json = json.dumps({'text':"中文"},ensure_ascii=False,indent=2)
    fout.write(dict_to_json + '\n')
    
    0 讨论(0)
  • 2020-11-27 10:58

    If you care about the speed use ujson (UltraJSON), which has the same API as json:

    import ujson
    ujson.dumps([{"key": "value"}, 81, True])
    # '[{"key":"value"},81,true]'
    ujson.loads("""[{"key": "value"}, 81, true]""")
    # [{u'key': u'value'}, 81, True]
    
    0 讨论(0)
  • 2020-11-27 10:59

    I think you should consider using the shelve module which provides persistent file-backed dictionary-like objects. It's easy to use in place of a "real" dictionary because it almost transparently provides your program with something that can be used just like a dictionary, without the need to explicitly convert it to a string and then write to a file (or vice-versa).

    The main difference is needing to initially open() it before first use and then close() it when you're done (and possibly sync()ing it, depending on the writeback option being used). Any "shelf" file objects create can contain regular dictionaries as values, allowing them to be logically nested.

    Here's a trivial example:

    import shelve
    
    shelf = shelve.open('mydata')  # open for reading and writing, creating if nec
    shelf.update({'one':1, 'two':2, 'three': {'three.1': 3.1, 'three.2': 3.2 }})
    shelf.close()
    
    shelf = shelve.open('mydata')
    print shelf
    shelf.close()
    

    Output:

    {'three': {'three.1': 3.1, 'three.2': 3.2}, 'two': 2, 'one': 1}
    
    0 讨论(0)
  • 2020-11-27 11:01

    Use the pickle module to save it to disk and load later on.

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

    I use json:

    import json
    
    # convert to string
    input = json.dumps({'id': id })
    
    # load to dict
    my_dict = json.loads(input) 
    
    0 讨论(0)
提交回复
热议问题