我有一个包含字典的列表,而字典又可能包含其他列表和/或字典,例如
a = [{3:4},{1:2}, {5:[5,6,7,7]} ]
我想创建此对象的哈希值(或等价物),以便将其与另一个哈希值进行比较,当列表内容不同时,该哈希值会有所不同。
我需要这个来通过网络进行查询。我不是一直在网络上提取可能非常大的列表,而是获得哈希值,只有当这个总和与前一个哈希值不同时,才能通过网络得到整个列表。
有没有简单的方法来实现这个目标?
答案 0 :(得分:2)
你可以使用泡菜
hashlib.md5(pickle.dumps(a[0])).hexdigest()
str并不总是给出预期的结果
答案 1 :(得分:1)
如何做:
# imports
import copy
def make_hash(x):
# Check if arg is a list, tuple or set
if isinstance(x, (set, tuple, list)):
return tuple([make_hash(y) for y in x])
# Check if arg is not a dict
elif not isinstance(x, dict):
return hash(x)
new = copy.deepcopy(x)
for k,v in new.items():
new[k] = make_hash(v)
return hash(tuple(frozenset(new.items())))
然后你可以做make_hash([{...},{...}])
答案 2 :(得分:0)
a = [{3:4},{1:2}, {5:[5,6,7,7]} ]
hash(str(a))