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.