Is there a Python equivalent of Java's Identit

2019-06-05 06:19发布

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.

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-06-05 06:53

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;
查看更多
Ridiculous、
3楼-- · 2019-06-05 06:54

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.

查看更多
Lonely孤独者°
4楼-- · 2019-06-05 06:56

Trivially:

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

Use the id of x as the dictionary key

查看更多
登录 后发表回答