for in sequence problem... possible new operator to add to python

Peter Hansen peter at engcorp.com
Thu Jul 10 12:35:50 EDT 2003


Adam Gent wrote:
> 
> I was fooling around subclassing a dictionary object and noticed that
> when
> I do the standard "for in <object-is-a-sequence>:" that I have no
> control on how python gets that sequence.
> 
> For example:
> 
> class Blah(dict):
>    pass
> 
> bl = Blah()
> 
> for b in bl:
>     #b will be a key and not a value
>     #no matter how I subclass Blah
> 
> However I want b to be the values with out doing:
> for b in bl.values()

Why do you want that?  That is not how Python works.  This is
sort of like saying "when I'm in my car and I push on the gas pedal,
the car moves.  However I want to make it move without pushing
on the gas pedal."

When you iterate over a dict in recent versions of Python, you 
are by definition iterating over the keys in the dict.  If you
want the values, you use .values(), and if you want both keys
and values, you use .items().  See the docs for more.

-Peter




More information about the Python-list mailing list