[Tutor] Iterating a dict with an iteration counter? How would *you* do it?
Modulok
modulok at gmail.com
Mon Feb 4 18:13:33 CET 2013
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-
More information about the Tutor
mailing list