[Tutor] Dict operation question.
Javier Ruere
javier at ruere.com.ar
Fri Jul 8 02:36:12 CEST 2005
David Driver wrote:
> I have a function
>
> def updateit(self,**mydict):
>
> which is intended to update a dictionary self.somedict.
>
> If there are keys in mydict that are not in self.somedict I want them
> returned in a new dict.
>
> here is what i am doing now:
>
> errdict = dict([(a,b) for a,b in mydict.items() if not a in self.somedict])
>
> I then test (if errdict) and raise an exception that contains errdict
> as an attribute. Else i update self.somedict.
>
> Is there something other than a list comprehension in a dict function
> that can do this?
>
> Thanks!
Hi,
You could have posted the code but anyway, this is your algorithm as I understood it:
class Test:
def __init__(self, dict):
self.somedict = dict
def updateit(self, **mydict):
errdict = dict([(a,b) for a,b in mydict.items() if not a in self.somedict])
if (not errdict):
raise Exception(errdict)
self.somedict.update(errdict)
The following implementation uses Sets to find the new keys and is slower (twice as slow).
from sets import Set
class Test:
def __init__(self, dict):
self.somedict = dict
def updateit(self, **mydict):
new = Set(mydict.iterkeys())
cur = Set(self.somedict.iterkeys())
diff = new - cur
for k in diff:
self.somedict[k] = mydict[k]
if (not diff):
raise Exception(errdict)
The last one uses dicts and is a bit faster than the original.
class Test:
def __init__(self, dict):
self.somedict = dict
def updateit(self, **mydict):
aux = mydict.copy()
aux.update(self.somedict)
size = len(self.somedict)
self.somedict.update(aux)
if (len(self.somedict) == size):
raise Exception({}) # It would be empty.
Javier
More information about the Tutor
mailing list