I would like to convert lists and dictionaries into bytes. I know that you can convert an string into bytes by doing:
"string".encode()
I would like to convert lists and dictionaries into bytes. I know that you can convert an string into bytes by doing:
"string".encode()
You can use bytearray for this.
nums = [1, 2, 3]
val = bytearray(nums)
print(val)
I think this will work fine. For dictionary and list you can also use the following code. I prefer this:
import json
d = {"a": "sldjkf", "b": "asod"}
s = json.dumps(d)
binary = ' '.join(format(ord(l), 'b') for l in s)
Use numpy's tobytes
:
l = [0.1, 1.0, 2.0]
A = np.array(l)
A.tobytes()
Result:
b'\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00'
For dictionaries you can use the method mentioned (json.dumps
) in the other answers to convert the dict
into string and then into bytes.
For list: you can use bytes() function from python.
For dictionaries: Convert dictionary to bytes and back again python?