Playing with Dict - Can anyone see a way around this?
s713221 at student.gu.edu.au
s713221 at student.gu.edu.au
Sun May 20 05:29:25 EDT 2001
Thanks Alex. I had to play around with the MyDict class to force update
of the keys, but this works as I wanted it to. I decided to leave out
the sort - mainly because of the desync between keys,values. (Items
would still be synched with keys, am I right?) Now I really should think
about wrapping these in UserDict and it's pals.
class MyDict:
def __init__(self):
self.dict = {}
self.__update()
def __getitem__(self,item):
return self.dict[item]
def __setitem__(self,item,value):
self.dict[item] = value
self.__update()
def __update(self):
self.keys = self.__keys(self.dict)
self.items = self.__items(self.dict)
self.values = self.__values(self.dict)
def __getattr__(self,key):
return self.dict[key]
def __repr__(self):
return str(self.dict)
def __delitem__(self,item):
del self.dict[item]
self.__update()
class __keys:
def __init__(self,dict):
self.keys = dict.keys()
def __repr__(self):
return repr(self.keys)
def __call__(self):
return self.keys
def __getitem__(self,item):
return self.keys[item]
class __items:
def __init__(self,dict):
self.items = dict.items()
def __repr__(self):
return repr(self.items)
def __call__(self):
return self.items
def __getitem__(self,item):
return self.items[item]
class __values:
def __init__(self,dict):
self.keys = dict.values()
def __repr__(self):
return repr(self.values)
def __call__(self):
return self.values
def __getitem__(self,item):
return self.values[item]
Charlie, I've had a look at the iterator PEP, and I like the idea of
optimised iterators for dictionaries, but I also like the original post
(months ago) that inspired this code, in that you don't have to remember
any new names for iteration over items/values etc. *shrugs* I'm not
particularly bothered how it's done, I was curious on how to do this,
and hey, I discovered that python doesn't use __getattr__ if the
attribute is in __dict__.
Joal Heagney/AncientHart
More information about the Python-list
mailing list