das passiert wenn einen die Langeweile packt...
Dachte mir ich implementiere mal eine kleine Dictionary-Klasse und das
ist dabei rausgekommen...
Hoffe
Code: Alles auswählen
"""My own dictionary class"""
class Dictionary ():
"This class is an alternative dictionary class."
def __init__ (self):
"The __init__ function creates the lists of the dictionary."
self.list_of_keys=[]
self.list_of_values=[]
def AddToDictionary (self,keys,values,position=None):
"""This function adds values and keys to your dictionary.
Keys and Values have to be lists.
The length of the lists MUST be the same."""
if len(keys) == len(values):
pass
if len(keys) > len(values):
raise ValueError, "Too much keys."
if len(keys) < len(values):
raise ValueError, "Too much values."
if position is None :
for i in range(len(keys)):
if self.HasKey(keys[i]) == 0:
pass
if self.HasKey(keys[i]) == 1:
raise ValueError, "Key already exists!"
self.list_of_keys.insert(len(self.list_of_keys)+len(keys),keys[i])
for a in range(len(values)):
if self.HasValue(values[a]) == 0:
pass
if self.HasValue(values[a]) == 1:
raise ValueError, "Value already exists!"
self.list_of_values.insert(len(self.list_of_values)+len(values),values[a])
if position is not None :
for i in range(len(keys)):
if self.HasKey(keys[i]) == 0:
pass
if self.HasKey(keys[i]) == 1:
raise ValueError, "Key already exists!"
self.list_of_keys.insert(position+len(keys),keys[i])
for a in range(len(values)):
if self.HasValue(values[a]) == 0:
pass
if self.HasValue(values[a]) == 1:
raise ValueError, "Value already exists!"
self.list_of_values.insert(position+len(values),values[a])
def HasKey (self,key):
"Finds out, if the Dictionary has the Key you are searching for."
try:
self.list_of_keys.index(key)
return 1
except ValueError:
return 0
def HasValue (self,value):
"Finds out, if the Dictionary has the Value you are searching for."
try:
self.list_of_values.index(value)
return 1
except ValueError:
return 0
def GiveMeValue (self,key):
"Gives you the value of the key you has entered."
if self.HasKey(key) == 1:
return self.list_of_values[self.list_of_keys.index(key)]
if self.HasKey(key) == 0:
raise ValueError, "This key doesn't exist."
def ShowDictionary(self):
for i in range(len(self.list_of_keys)):
print i,"key",self.list_of_keys[i],"value",self.list_of_values[i]
funktioniert...

MfG Jonas