[Tutor] Remove a dictionary entry

Alan Gauld alan.gauld at btinternet.com
Sat Sep 18 10:35:49 CEST 2010


"M. 427" <427 at free.fr> wrote

> I ended up with this :
>
> Version 3 :
> for i,row in d[:].iteritems() : # BUG : TypeError: unhashable type
>    if len(row) < 2 :
>        del d[i]

You are getting too complicated.
You don't need the slice and you don't need iteritems.
You have a dictionary. When you iterate over a dictionary
what do you get? Don't know? Try it::

>>> for x in {1:'foo',2:'bar'}: print x
...
1
2

So we get the keys. Now how do we use the keys to get the list?
Standard dictionary access:

>>> print d[1]
foo

You know how to test the lenth of the list and delete the list so put
that together as you did before:

for row in d :     # row is actually the key
   if len(row) == 1 :        # so use the key to get the real row
     del row # WRONG      #' and delete the row, again using the key

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list