📅 2010-Jan-25 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ dictionaries, iteration, python ⬩ 📚 Archive
The default iteration through a dictionary, returns the keys:
adict = {10:"Ten", 7:"Seven", 12:"Twelve"}
for i in adict:
print(i)
Output:
10
12
7
(Note that the order of the keys is different from the order in the initialization. This is normal behaviour for a dictionary, where order of the elements should not matter or be relied upon.)
Explicit iteration of the dictionary keys, values and (key, value) pairs can also be done:
# Iterate keys
for k in adict.keys():
print(k)
# Iterate values
for v in adict.values():
print(v)
# Iterate (key, value) pairs
for (k, v) in adict.items():
print(k, ":", v)
Output:
10
12
7
Ten
Twelve
Seven
10 : Ten
12 : Twelve
7 : Seven