[Tutor] Remove a dictionary entry

Peter Otten __peter__ at web.de
Sun Sep 19 10:45:34 CEST 2010


M. 427 wrote:

> Version 4 : (2 steps)
> 
>         # step 1 : list keys of unwanted rows
>         sck=[] # list of single children keys in dictionary
>         for k in d.keys() :
>                 if len(d[k]) < 2 :
>                         sck.append(k)
>         # step 2 : delete all d rows whose key is listed in sck
>         while len(sck) > 0 :
>                 del d[sck.pop()]
> 
> This works.
> Is this the optimal pythonic way of doing it?

Ceterum censeo: the pythonic way is to make a copy:

d = dict((k, v) for k, v in d.iteritems() if len(v) > 1)

As an optimization, if the dictionary is huge and there are relatively few 
items to be deleted you may fall back to the 2-step approach. I would write 
it

delenda = [k for k, v in d.iteritems() if len(v) < 2]
for k in delenda:
    del d[k]

Peter



More information about the Tutor mailing list