Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 596
TIMEX Avatar asked Dec 03 '10 03:12

TIMEX


People also ask

How do you serialize a dictionary in Python?

The standard solution for serializing and deserializing a Python dictionary is with the pickle module. The dumps() function serialize a Python object by converting it into a byte stream, and the loads() function do the inverse, i.e., convert the byte stream back into an object.

Can we convert string to dictionary in Python?

You can easily convert python string to the dictionary by using the inbuilt function of loads of json library of python. Before using this method, you have to import the json library in python using the “import” keyword.

How do I convert a string to a dictionary?

To convert a Python string to a dictionary, use the json. loads() function. The json. loads() is a built-in Python function that converts a valid string to a dict.

How can you copy the entire dictionary to a new dictionary?

The dict. copy() method returns a shallow copy of the dictionary. The dictionary can also be copied using the = operator, which points to the same object as the original. So if any change is made in the copied dictionary will also reflect in the original dictionary.


2 Answers

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: <object object at 0x7fa0348230c0> is not JSON serializable 
like image 123
Chris Morgan Avatar answered Sep 30 '22 05:09

Chris Morgan


Pickle is great but I think it's worth mentioning literal_eval from the ast module for an even lighter weight solution if you're only serializing basic python types. It's basically a "safe" version of the notorious eval function that only allows evaluation of basic python types as opposed to any valid python code.

Example:

>>> d = {} >>> d[0] = range(10) >>> d['1'] = {} >>> d['1'][0] = range(10) >>> d['1'][1] = 'hello' >>> data_string = str(d) >>> print data_string {0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], '1': {0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 1: 'hello'}}  >>> from ast import literal_eval >>> d == literal_eval(data_string) True 

One benefit is that the serialized data is just python code, so it's very human friendly. Compare it to what you would get with pickle.dumps:

>>> import pickle >>> print pickle.dumps(d) (dp0 I0 (lp1 I0 aI1 aI2 aI3 aI4 aI5 aI6 aI7 aI8 aI9 asS'1' p2 (dp3 I0 (lp4 I0 aI1 aI2 aI3 aI4 aI5 aI6 aI7 aI8 aI9 asI1 S'hello' p5 ss. 

The downside is that as soon as the the data includes a type that is not supported by literal_ast you'll have to transition to something else like pickling.

like image 40
Graphics Noob Avatar answered Sep 30 '22 04:09

Graphics Noob