[Tutor] Iterating a dict with an iteration counter? How would *you* do it?
Dave Angel
davea at davea.name
Mon Feb 4 18:28:38 CET 2013
On 02/04/2013 12:13 PM, Modulok wrote:
> List,
>
> Simple question: Is there a common pattern for iterating a dict, but also
> providing access to an iteration counter? Here's what I usually do (below). I'm
> just wondering if there are other, more clever ways::
>
> data = {'a': "apple", 'b': "banana", 'c': "cherry"}
> i = 0
> for k,v in data.items():
> print("i: %s, k: %s, v: %s" % (i,k,v))
> i += 1
>
> Another variant, same idea::
>
> data = {'a': "apple", 'b': "banana", 'c': "cherry"}
> for i,k,v in zip(range(len(data)), data.keys(), data.values()):
> print("i: %s, k: %s, v: %s" % (i,k,v))
>
>
> How would you do it?
> -Modulok-
enumerate()
for i, (k, v) in enumerate(data.items()):
--
DaveA
More information about the Tutor
mailing list