That's the first I've read of iterating through dictionaries, I'd
assumed it was impossible because they're unordered. Your explanation
for defining your own iterables is much easier to understand than the
one I read before as well.

Thanks again.

2010/4/19 spir ☣ <denis.s...@gmail.com>:
> On Mon, 19 Apr 2010 00:37:11 +0100
> C M Caine <cmca...@googlemail.com> wrote:
>
>> That's two new things I've learnt. I didn't realise that for loops
>> could be used like that (with more than one... key?).
>
> Consider considering things differently: a for loop always iterates over 
> items of a collection you indicate:
>
> l = [1,2,3]
> # item is list item             (implicit, it could be written items(l) or 
> l.items())
> for n in l: print n,
> # item is (index,item) pair
> for (i,n) in enumerate(l): print (i,n),
> print
>
> d = {'a':1, 'b':2, 'c':3}
> # item is dict key              (implicit, it could be written d.keys())
> for k in d: print k,
> # item is dict value
> for v in d.values(): print v,
> # item is (key,value) pair
> for (k,v) in d.items(): print (k,v),
> print
>
> (In the last case "items()" is maybe a bit confusing.)
>
> Python lets you construct your own iterators on custom collections to iterate 
> in a different way:
> class NestedList(list):
>        def __iter__(self):
>                ll = list.__iter__(self)
>                for l in ll:
>                        for item in l:
>                                yield item
> ll = NestedList([[1,2,3], [9,8]])
> for n in ll: print n,
>
> Denis
> ________________________________
>
> vit esse estrany ☣
>
> spir.wikidot.com
>
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to