为了缓存目的,我需要从字典中存在的GET参数生成一个缓存键。

目前,我正在使用sha1(repr(sorted(my_dict.items()))) (sha1()是一个内部使用hashlib的方便方法),但我很好奇是否有更好的方法。


当前回答

更新自2013年回复…

以上答案在我看来都不可靠。原因是使用了items()。据我所知,这是一个依赖于机器的顺序。

这个怎么样?

import hashlib

def dict_hash(the_dict, *ignore):
    if ignore:  # Sometimes you don't care about some items
        interesting = the_dict.copy()
        for item in ignore:
            if item in interesting:
                interesting.pop(item)
        the_dict = interesting
    result = hashlib.sha1(
        '%s' % sorted(the_dict.items())
    ).hexdigest()
    return result

其他回答

如果你的字典不是嵌套的,你可以用字典的项创建一个frozenset,并使用hash():

hash(frozenset(my_dict.items()))

与生成JSON字符串或字典表示相比,这需要的计算量要小得多。

更新:请参阅下面的评论,为什么这种方法可能不会产生稳定的结果。

解决这个问题的一种方法是用字典的元素创建一个元组:

hash(tuple(my_dict.items()))

使用DeepDiff模块中的DeepHash

from deepdiff import DeepHash
obj = {'a':'1',b:'2'}
hashes = DeepHash(obj)[obj]

您可以使用地图库来做到这一点。具体来说,地图。FrozenMap

import maps
fm = maps.FrozenMap(my_dict)
hash(fm)

要安装地图,只需执行:

pip install maps

它也处理嵌套的dict大小写:

import maps
fm = maps.FrozenMap.recurse(my_dict)
hash(fm)

免责声明:我是地图库的作者。

我是这样做的:

hash(str(my_dict))