for in sequence problem... possible new operator to add to py thon

sismex01 at hebmex.com sismex01 at hebmex.com
Thu Jul 10 13:07:20 EDT 2003


> From: Peter Hansen [mailto:peter at engcorp.com] 
> Sent: Jueves, 10 de Julio de 2003 11:36 a.m.
> 
> Adam Gent wrote:
> > [..snippage..]
> 
> [..more.snippage..]
>
> 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
>

Actually, .keys(), .values() and .items() return their respective
lists, in arbitrary order.

If you wish to use an iterator, use .iterkeys() , .itervalues()
or .iteritems() ; very helpful in the case of big dictionaries,
since you don't need to create and then destroy big lists.

Adam: If you wish to iterate through the items by default,
have you tried something like this?

class NewDict(dict):
    def __iter__(self):
        return super(NewDict,self).itervalues()

That should, by default (like "for x in nd:") iterate through
the values of a dictionary, instead of it's keys.

I haven't tested it though, so caveat emptor.

-gustavo
Advertencia:La informacion contenida en este mensaje es confidencial y
restringida, por lo tanto esta destinada unicamente para el uso de la
persona arriba indicada, se le notifica que esta prohibida la difusion de
este mensaje. Si ha recibido este mensaje por error, o si hay problemas en
la transmision, favor de comunicarse con el remitente. Gracias.





More information about the Python-list mailing list