I had the need to implement a hashable dict so I could use a dictionary as a key for another dictionary.
A few months ago I used this implementation: Python hashable
If you are only using it as a key for another dict
, you could go for frozenset(mutabledict.items())
. If you need to access the underlying mappings, you could then use that as the parameter to dict
.
mutabledict = dict(zip('abc', range(3)))
immutable = frozenset(mutabledict.items())
read_frozen = dict(immutable)
read_frozen['a'] # => 1
Note that you could also combine this with a class derived from dict
, and use the frozenset
as the source of the hash, while disabling __setitem__
, as suggested in another answer. (@RaymondHettinger's answer for code which does just that).