Is there a Python equivalent of Java's IdentityHashMap?

浪子不回头ぞ 提交于 2019-12-08 04:53:06

问题


I'm walking a data structure and would like to build a dict mapping X->Y, where X is a field in the data structure I'm walking and Y is a field in the data structure I'm building on the fly. X is an unhashable type.


回答1:


Trivially:

idmap = {}
idmap[id(x)] = y

Use the id of x as the dictionary key




回答2:


The purpose of Java's IdentityHashMap is to simulate dynamic field. Since Python language already supports dynamic attributes directly, you don't need the map, just assign Y to an X's attribute

x.someSuchRelation = y;



回答3:


You can just use a regular Python dict for this if you wrap your unhashable objects in another object. Specifically, something like this:

class Wrapper(object):
    def __init__(self, o):
        self.o = o

    def __hash__(self):
        return id(self.o)

    def __eq__(self, o):
        return hash(self) == hash(o)

Then just use it like some_dict[Wrapper(unhashable_object)].

This is a more useful approach than just using id(o) as the key if you also need to be able to access the object itself afterwards (as key.o, obviously). If you don't (and garbage collection isn't an issue), just use that.



来源:https://stackoverflow.com/questions/17054084/is-there-a-python-equivalent-of-javas-identityhashmap

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