Convert dictionary to bytes and back again python? [duplicate]
This should work:
s=json.dumps(variables)variables2=json.loads(s)assert(variables==variables2)
If you need to convert the dictionary to binary, you need to convert it to a string (JSON) as described in the previous answer, then you can convert it to binary.
For example:
my_dict = {'key' : [1,2,3]}import jsondef dict_to_binary(the_dict): str = json.dumps(the_dict) binary = ' '.join(format(ord(letter), 'b') for letter in str) return binarydef binary_to_dict(the_binary): jsn = ''.join(chr(int(x, 2)) for x in the_binary.split()) d = json.loads(jsn) return dbin = dict_to_binary(my_dict)print bindct = binary_to_dict(bin)print dct
will give the output
1111011 100010 1101011 100010 111010 100000 1011011 110001 101100 100000 110010 101100 100000 110011 1011101 1111101{u'key': [1, 2, 3]}