Jup! Jetzt geht's...
Damit man nicht den ganzen Thread durchlesen muß, hier nochmal die aktuelle Version, mit allen Verbesserungen:
Code: Alles auswählen
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Modul: Lict
Description: Mix of list and dict
Version: 0.1.1
Copyright: 2004 by Fritz Cizmarov fritz@sol.at
Created: 16. Nov. 2004
Last modified: 20. Nov. 2004
License: free
Requirements: Python2.3
Exports: Classes and Functions to export
"""
class Index(int):
""" Helperclass for access Lict by Index """
__slots__ = []
class Lict(dict):
__slots__ = ["__keylist"]
def __init__(self, *args, **kw):
super(Lict, self).__init__(*args, **kw)
self.__keylist = []
if len(args) == 1 and isinstance(args[0], (tuple, list)):
for key, value in args[0]:
self.__keylist.append(key)
for key in kw:
self.__keylist.append(key)
def __getitem__(self, key):
if type(key) is Index:
key = self.__keylist[key]
return super(Lict, self).__getitem__(key)
def __setitem__(self, key, value):
""" sets item, if item not exists append it """
if type(key) is Index:
key = self.__keylist[key]
elif key not in self.__keylist:
self.__keylist.append(key)
super(Lict, self).__setitem__(key, value)
def __delitem__(self, key):
if type(key) is Index:
key = self.__keylist[key]
super(Lict, self).__delitem__(key)
del self.__keylist[ self.__keylist.index(key) ]
def insert(self, index, key, value):
self.__keylist.insert(index, key)
super(Lict, self).__setitem__(key, value)
def __str__(self):
tpl = "{"+("%s : %s, "*len(self.__keylist))[:-2]+"}"
if self.__keylist:
data = [repr(x) for x in reduce(lambda a, b: a+b, self.iteritems())]
return tpl % tuple(data)
else:
return tpl
def __repr__(self):
tpl = "Lict(["+("(%s, %s), "*len(self.__keylist))[:-2]+"])"
if self.__keylist:
data = [repr(x) for x in reduce(lambda a, b: a+b, self.iteritems())]
return tpl % tuple(data)
else:
return tpl
def __iter__(self):
return iter(self.__keylist)
def iteritems(self):
for key in self.__keylist:
yield key, self[key]
iterkeys = __iter__
def itervalues(self):
for key in self.__keylist:
yield self[key]
def update(self, E):
if not isinstance(E, Lict):
raise TypeError("E is not from type Lict!")
for key in E:
self[key] = E[key]
def pop(self, key=None):
if key is None:
key = self.__keylist[-1]
elif type(key) is Index:
key = self.__keylist[key]
self.keylist.remove(key)
return super(Lict, self).pop(key)
def reverse(self):
self.__keylist.reverse()
def sort(self):
self.__keylist.sort()
if __name__=="__main__":
print "->",__file__,"<- SelbstTest\n"
def LictAusgeben():
print "="*40
for k,v in MyLict.iteritems():
print k,"-",v
print "="*40
MyLict = Lict()
MyLict["Key1"]="Wert1"
MyLict["Key2"]="Wert2"
MyLict["Key3"]="Wert3"
LictAusgeben()
MyLict["Key2"]="Wert2XX"
MyLict["Key4"]="Wert4"
MyLict["Key5"]="Wert5"
LictAusgeben()
del( MyLict["Key2"] )
LictAusgeben()
MyLict.insert(2, "Key2", "Wert2NEU")
LictAusgeben()