as others have pointed out, iterating over a dict
iterates through it's keys in no particular order.
As you can see here
>>> d = {'x': 1, 'y': 2, 'z': 3}
>>> list(d)
['y', 'x', 'z']
>>> d.keys()
['y', 'x', 'z']
For your example it is a better idea to use dict.items()
>>> d.items()
[('y', 2), ('x', 1), ('z', 3)]
This gives you a list of tuples. When you loop over them like this, each tuple is unpacked into k
and v
automatically
for k,v in d.items():
print k, 'corresponds to', v
Using k
and v
as variable names when looping over a dict
is quite common if the body of the loop is only a few lines. For more complicated loops it may be a good idea to use more descriptive names
for letter, number in d.items():
print letter, 'corresponds to', number
It's a good idea going forward to get into the habit of using format strings
for letter, number in d.items():
print '{0} corresponds to {1}'.format(letter, number)