将字典转换为字节并再次返回 python?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19232011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert dictionary to bytes and back again python?
提问by user1205406
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.
我需要在两台机器之间发送一些变量的值,并打算使用套接字来完成。我使用 md5 哈希算法作为我发送的数据的校验和,以确保数据正确传输。要执行 md5 哈希算法,我必须将数据转换为字节。我想同时传输变量的名称及其值。因为我有很多变量,所以我使用字典。
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.
我已经尝试了几种不同的方法 json 在这里推荐(将 python dict 转换为字符串并返回),但我无法缝合以生成一个字符串,不管字节。
采纳答案by Rob?
This should work:
这应该有效:
s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)
回答by shshank
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.
如果您需要将字典转换为二进制,则需要按照上一个答案中的描述将其转换为字符串(JSON),然后才能将其转换为二进制。
For example:
例如:
my_dict = {'key' : [1,2,3]}
import json
def dict_to_binary(the_dict):
str = json.dumps(the_dict)
binary = ' '.join(format(ord(letter), 'b') for letter in str)
return binary
def binary_to_dict(the_binary):
jsn = ''.join(chr(int(x, 2)) for x in the_binary.split())
d = json.loads(jsn)
return d
bin = dict_to_binary(my_dict)
print bin
dct = 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]}