Set of Dictionary
Piet van Oostrum
piet at cs.uu.nl
Thu Jun 16 11:45:12 EDT 2005
>>>>> Vibha Tripathi <vibtrip at yahoo.com> (VT) wrote:
>VT> Hi Folks,
>VT> I know sets have been implemented using dictionary but
>VT> I absolutely need to have a set of dictionaries...any
>VT> ideas how to do that?
A set cannot contain duplicates. What happens when one of the dictionaries
in the set is modified in such a way that it becomes equal to another
element?
Maybe you just need a list of dictionaries? Or maybe you want immutable
dictionaries to put in the set. In that case you can define your own
immutable dictionary class that defines a hash function. Ideally you would
redefine the dictionary modification methods to make them generate error
messages. For safety in the following code a copy is made of the dict.
The values in the dict must be hashable, which usually means immutable.
class immdict(dict):
def __init__(self, somedict):
self.data = somedict.copy()
def __hash__(self):
result = 0
for elt in self.data:
result ^= hash(elt) ^ hash(self.data[elt])
return result
def __repr__(self):
return repr(self.data)
__str__ = __repr__
d = immdict({1:0, 2:3})
s = Set()
s.add(d)
--
Piet van Oostrum <piet at cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: piet at vanoostrum.org
More information about the Python-list
mailing list