How to Iterate over a Dictionary in Python 3

To iterate over this dictionary (similar to a hash, or map in other languages):

words = {
    'a': 'apple',
    'b': 'banana',
    'c': 'car'
}

you can use the items() method:

for letter, word in words.items():
    print('{0}: {1}'.format(letter, word))

The result is:

c: car
a: apple
b: banana

Note the keys are not sorted.

Comments

Leave a comment

What color are brown eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.