Immutable dictionary, only use as a key for another dictionary

前端 未结 8 2334
情歌与酒
情歌与酒 2020-12-05 04:52

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

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 05:05

    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).

提交回复
热议问题