Python,字典的校验和 [英] Python, checksum of a dict

查看:144
本文介绍了Python,字典的校验和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑创建一个字典的校验和,以了解它是否已被修改
目前,我知道:

I'm thinking to create a checksum of a dict to know if it was modified or not For the moment i have that:

>>> import hashlib
>>> import pickle
>>> d = {'k': 'v', 'k2': 'v2'}
>>> z = pickle.dumps(d)
>>> hashlib.md5(z).hexdigest()
'8521955ed8c63c554744058c9888dc30'

也许是一个更好的解决方案存在吗?

Perhaps a better solution exists?

注意:我想创建一个字典的唯一ID以创建良好的Etag。

编辑::我可以在字典中包含抽象数据。

I can have abstract data in the dict.

推荐答案

像这样的东西:

reduce(lambda x,y : x^y, [hash(item) for item in d.items()])

对dict中的每个(键,值)元组进行散列并对其进行XOR

Take the hash of each (key, value) tuple in the dict and XOR them alltogether.

@katrielalex
如果字典包含不可散列的项目,则可以执行以下操作:

@katrielalex If the dict contains unhashable items you could do this:

hash(str(d))

甚至更好

hash(repr(d))

这篇关于Python,字典的校验和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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