A workaround for Python's missing frozen-dict type? [duplicate]

怎甘沉沦 提交于 2019-12-18 19:39:59

问题


In Python, when you want to use lists as keys of some dictionary, you can turn them into tuples, which are immutable and hence are hashable.

>>> a = {}
>>> a[tuple(list_1)] = some_value
>>> a[tuple(list_2)] = some_other_value

The same happens when you want to use set objects as keys of some dictionary - you can build a frozenset, that is again immutable and hence is hashable.

>>> a = {}
>>> a[frozenset(set_1)] = some_value
>>> a[frozenset(set_2)] = some_other_value

But it seems that for dictionary there is no equivalent.

A first idea I thought about (and found it bad finally), is to use str(some_dict) as a key. But, dictionaries always use different hash functions, so strings of equal dictionaries may be different.

Is there any workaround known as a good practice, or does anyone have other ideas how to use dictionary-like objects as keys of other dictionaries?


回答1:


I've found a nice workaround for this problem, which is building a frozenset containing the dictionary items:

>>> a = {'key1' : 'val1', 'key2' : 'val2'}
>>> b = frozenset(a.items())
>>> frozenset_restored_to_dict = dict(b)
>>> frozenset_restored_to_dict
{'key2': 'val2', 'key1': 'val1'}

As can be seen in the code, b is a frozenset, which is immutable and hashable, and can be totally restored to be a regular dictionary like a.




回答2:


You can try ordered dict or look on these answers:

  • What would a "frozen dict" be?
  • Immutable dictionary, only use as a key for another dictionary
  • How to create an immutable dictionary in python?

and there is even a package on PyPI: https://pypi.python.org/pypi/frozendict

You can also simply convert dict to tuples(sorted(your_dict.items())) and then use as a hash.

UPD: as mentioned in comments, OrderedDict is unhashable. My bad, it is really should not be hashable since it is mutable.



来源:https://stackoverflow.com/questions/39440190/a-workaround-for-pythons-missing-frozen-dict-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!