Using non-hashable Python objects as keys in dictionaries

后端 未结 8 1569
栀梦
栀梦 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:12

    Based off solution by Chris Lutz. Note that this doesn't handle objects that are changed by iteration, such as streams, nor does it handle cycles.

    import collections
    
    def make_hashable(obj):
        """WARNING: This function only works on a limited subset of objects
        Make a range of objects hashable. 
        Accepts embedded dictionaries, lists or tuples (including namedtuples)"""
        if isinstance(obj, collections.Hashable):
            #Fine to be hashed without any changes
            return obj
        elif isinstance(obj, collections.Mapping):
            #Convert into a frozenset instead
            items=list(obj.items())
            for i, item in enumerate(items):
                    items[i]=make_hashable(item)
            return frozenset(items)
        elif isinstance(obj, collections.Iterable):
            #Convert into a tuple instead
            ret=[type(obj)]
            for i, item in enumerate(obj):
                    ret.append(make_hashable(item))
            return tuple(ret)
        #Use the id of the object
        return id(obj)
    

提交回复
热议问题