将字典转换为字节然后再次返回python? [英] Convert dictionary to bytes and back again python?

查看:150
本文介绍了将字典转换为字节然后再次返回python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在两台机器之间发送一些变量的值,并打算使用套接字来实现.我使用md5哈希算法作为发送数据的校验和,以确保正确传输数据.要执行md5哈希算法,我必须将数据转换为字节.我想同时传递变量的名称和它的值.因为我有很多变量,所以我使用字典.

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.

所以我想将类似这样的内容转换为字节?

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.

我尝试了几种不同的方法,在这里推荐使用json(将python字典转换为字符串然后返回),但我无法通过接缝生成一个字符串,不用管它是字节.

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.

推荐答案

这应该有效:

s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)

这篇关于将字典转换为字节然后再次返回python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆