[Tutor] Dict operation question.

Kent Johnson kent37 at tds.net
Fri Jul 8 15:37:38 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?

What's wrong with using the list comprehension? It is terse and readable. If speed is a concern, you can use mydict.iteritems() instead of mydict.items() and in Python 2.4 you can use a generator comprehension instead of a list comprehension:

errdict = dict((a,b) for a,b in mydict.iteritems() if not a in self.somedict)

Both of these changes eliminate creation of intermediate lists.

Kent



More information about the Tutor mailing list