Hashing a dictionary?

dictionary, hash, python

Solution

If your dictionary is not nested, you could make a frozenset with the dict's items and use `hash()`:

hash(frozenset(my_dict.items()))

This is much less computationally intensive than generating the JSON string or representation of the dictionary.

UPDATE: Please see the comments below, why this approach might not produce a stable result.

Problem

For caching purposes I need to generate a cache key from GET arguments which are present in a dict. Currently I'm using `sha1(repr(sorted(my_dict.items())))` (`sha1()` is a convenience method that uses hashlib internally) but I'm curious if there's a better way.

Original source

Related problems