Using non-hashable Python objects as keys in dictionaries

后端 未结 8 1573
栀梦
栀梦 2020-12-19 16:00

Python doesn\'t allow non-hashable objects to be used as keys in other dictionaries. As pointed out by Andrey Vlasovskikh, there is a nice workaround for the special case of

8条回答
  •  无人及你
    2020-12-19 16:17

    With recursion!

    def make_hashable(h):
        items = h.items()
        for item in items:
            if type(items) == dict:
                item = make_hashable(item)
        return frozenset(items)
    

    You can add other type tests for any other mutable types you want to make hashable. It shouldn't be hard.

提交回复
热议问题