How do I serialize a Python dictionary into a string, and then back to a dictionary?

前端 未结 8 1034
我在风中等你
我在风中等你 2020-11-29 20:46

How do I serialize a Python dictionary into a string, and then back to a dictionary? The dictionary will have lists and other dictionaries inside it.

8条回答
  •  执念已碎
    2020-11-29 21:38

    It depends on what you're wanting to use it for. If you're just trying to save it, you should use pickle (or, if you’re using CPython 2.x, cPickle, which is faster).

    >>> import pickle
    >>> pickle.dumps({'foo': 'bar'})
    b'\x80\x03}q\x00X\x03\x00\x00\x00fooq\x01X\x03\x00\x00\x00barq\x02s.'
    >>> pickle.loads(_)
    {'foo': 'bar'}
    

    If you want it to be readable, you could use json:

    >>> import json
    >>> json.dumps({'foo': 'bar'})
    '{"foo": "bar"}'
    >>> json.loads(_)
    {'foo': 'bar'}
    

    json is, however, very limited in what it will support, while pickle can be used for arbitrary objects (if it doesn't work automatically, the class can define __getstate__ to specify precisely how it should be pickled).

    >>> pickle.dumps(object())
    b'\x80\x03cbuiltins\nobject\nq\x00)\x81q\x01.'
    >>> json.dumps(object())
    Traceback (most recent call last):
      ...
    TypeError:  is not JSON serializable
    
        

    提交回复
    热议问题