dictionary - objects as keys in python dictionaries -
i'm trying use object key in python dictionary, it's behaving in way can't quite understand.
first create dictionary object key:
package_disseminators = { contenttype("application", "zip", "http://other/property") : "one", contenttype("application", "zip") : "two" }
now create object "the same" 1 key.
content_type = contenttype("application", "zip", "http://other/property")
i have given contenttype object custom __eq__
, custom __str__
methods, such __eq__
method compares __str__
values.
now, interactive python:
>>> key in package_disseminators: ... if key == content_type: ... print "match" ... else: ... print "no match" ... no match match >>> content_type in package_disseminators.keys() true
ok, looks object being identified key, so:
>>> package_disseminators[content_type] traceback (most recent call last): file "<stdin>", line 1, in <module> keyerror: (& (type="application/zip") (packaging="http://other/property") )
er ... ok? content_type in package_disseminators.keys() list, isn't key?
>>> package_disseminators.has_key(content_type) false
apparently not.
i presume comparison process python uses determin equality differs between straight "in" statement on list , looking key in dict, don't know how. tips or insights?
from python documentation:
a dictionary’s keys arbitrary values. values not hashable, is, values containing lists, dictionaries or other mutable types (that compared value rather object identity) may not used keys.
hashable defined follows
an object hashable if has hash value never changes during lifetime (it needs
__hash__()
method), , can compared other objects (it needs__eq__()
or__cmp__()
method). hashable objects compare equal must have same hash value.hashability makes object usable dictionary key , set member, because these data structures use hash value internally.
so if want this, need override default __hash__()
method on object (see comment steven rumbalski below further explanation).
>>> content_type in package_disseminators.keys() true
i suppose works because dict.keys()
returns list, , __contains__
checks equality, not same hashes.
Comments
Post a Comment