[Tutor] Iterating a dict with an iteration counter? How would *you* do it?

Modulok modulok at gmail.com
Mon Feb 4 18:58:10 CET 2013


Hmm.. no kidding. Well, at least I knew I was over-complicating it.

Cheers!
-Modulok-


On 2/4/13, Dave Angel <davea at davea.name> wrote:
> 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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list