如何将列表和字典转换为字节?

时间:2020-05-20 15:33:05

标签: python python-3.x

我想将列表和字典转换为字节。 我知道您可以通过以下方式将字符串转换为字节:

"string".encode()

3 个答案:

答案 0 :(得分:1)

您可以为此使用字节数组。

nums = [1, 2, 3]
val = bytearray(nums)

print(val)

我认为这会很好。对于字典和列表,您还可以使用以下代码。我喜欢这个:

import json

d = {"a": "sldjkf", "b": "asod"}
s = json.dumps(d)
binary = ' '.join(format(ord(l), 'b') for l in s)

答案 1 :(得分:1)

使用numpy的tobytes

l = [0.1, 1.0, 2.0]
A = np.array(l)
A.tobytes()

结果:

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'

对于字典,您可以使用其他答案中提到的方法(json.dumpsdict转换为字符串,然后转换为字节。

答案 2 :(得分:0)

对于列表: 您可以使用python中的bytes()函数。

对于字典: Convert dictionary to bytes and back again python?