[Tutor] Remove a dictionary entry
Alan Gauld
alan.gauld at btinternet.com
Sat Sep 18 17:03:43 CEST 2010
"Alan Gauld" <alan.gauld at btinternet.com> 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
>
Oops, as Peter pointed out that won't work because its changing
the iterable while we iterate. (I actually thought it would be OK
because the for would use a copy of the keys() list, but I was
wrong...)
But you can fix that with a list() call:
for row in list(d) : # generates a new list of the dict keys
if len(d[row]) == 1 : # so use the key to get the real row
del d[row]
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list