Python: Dictionary Iteration

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
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.