1

I would like to convert lists and dictionaries into bytes. I know that you can convert an string into bytes by doing:

"string".encode()
Creepi
  • 21
  • 6
  • use ```json.dumps``` convert to string then you should be able to apply encode on it. – sushanth May 20 '20 at 15:34
  • @Sushanth Why did I not think of that. Thank you! – Creepi May 20 '20 at 15:36
  • There are several serialization protocols out there. The one with arguably the most coverage of python data structures is its own `pickle`. If you are dealing with elementary types, json or protobuf or msgpack come to mind. But there are other ways to save such as HDF5, parquet, willow, ... A SQL database or mongo db may be reasonable. Just saying, there are a hundred ways to do this. – tdelaney May 20 '20 at 15:38
  • What do you mean by "convert"? What problem do you hope to solve by doing this? In particular, what do you hope to do with the resulting bytes? The best approach to the problem depends on the exact purpose. – Karl Knechtel May 20 '20 at 16:07

3 Answers3

1

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)
Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49
Protik Nag
  • 511
  • 5
  • 20
1

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.

Code Pope
  • 5,075
  • 8
  • 26
  • 68
0

For list: you can use bytes() function from python.

For dictionaries: Convert dictionary to bytes and back again python?