问题
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