Using non-hashable Python objects as keys in dictionaries

后端 未结 8 1550
栀梦
栀梦 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.

    0 讨论(0)
  • 2020-12-19 16:18

    I agree with Lennart Regebro that you don't. However I often find it useful to cache some function calls, callable object and/or Flyweight objects, since they may use keyword arguments.

    But if you really want it, try pickle.dumps (or cPickle if python 2.6) as a quick and dirty hack. It is much faster than any of the answers that uses recursive calls to make items immutable, and strings are hashable.

    import pickle
    hashable_str = pickle.dumps(unhashable_object)
    
    0 讨论(0)
提交回复
热议问题