Convert dictionary to bytes and back again python?

user1205406 picture user1205406 · Oct 7, 2013 · Viewed 104.3k times · Source

I need to send the value of some variables between two machines and intend to do it using sockets. I use the md5 hash algorithm as a checksum for the data I send to ensure the data is correctly transmitted. To perform the md5 hash algorithm I have to convert the data to bytes. I want to transmit both the name of the variable and its value. As I have a lot of variables i use a dictionary.

So I want to convert something like this to bytes?

variables = {'var1' : 0, 'var2' : 'some string', 'var1' : ['listitem1','listitem2',5]}

In other words I have a dictionary with a lot of different data types inside it including lists which in turn have multiple different data types in them and I want to convert that into bytes. Then on the receiving machine convert those bytes back into a dictionary.

I have tried a few different methods json is recomended here (Convert a python dict to a string and back) but I can't seam to produce a string with it never mind bytes.

Answer

Robᵩ picture Robᵩ · Oct 7, 2013

This should work:

s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)