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

Sean Ross sross at
Thu Jul 10 19:03:35 CEST 2003

"Adam Gent" <agentgt at> wrote in message
news:3a8fc6c5.0307100816.634c83a3 at
> 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.
> However I want b to be the values with out doing:
> for b in bl.values()

You can do it as follows:

class Blah(dict):
    def __iter__(self):
        return iter(self.values())

b = Blah()
b.update({'hello':'world', 'how':'are', 'you':'today'})
for v in b:
    print v

# are
# today
# world

Just be aware that you are introducing surprising behaviour - other Python
programmers will expect

for v in b:

to iterate thru the keys of b, not the values. It's up to you whether you
want this behaviour more than you want your code to be easily understood.

More information about the Python-list mailing list