5️⃣

9.5 Iterating Through Dictionaries

Iterating Through Dictionaries

Iterating through dictionaries is very similar to iterating through lists - that is, you can use for loops.

You should be familiar with the following methods to iterate through dictionaries:

  • keys
  • values
  • items
# Iterating Through Dictionaries

contacts = {"Daisy Johnson": "2468 Park Ave", "Leo Fitz": "1258 Monkey Dr"}

# iterate through each key
for name in contacts:
    print(name)

# or, use keys() method
for name in contacts.keys():
    print(name)

# using each key to print each value
for name in contacts:
    # prints each address associated with each name
    print(contacts[name])

# iterate through each value using values()
for address in contacts.values():
    print(address)

# iterate through keys and values using items()
for name, address in contacts.items():
    print(name + ", " + address)

View code on GitHub.

Output of the above code:

Daisy Johnson
Leo Fitz
Daisy Johnson
Leo Fitz
2468 Park Ave
1258 Monkey Dr
2468 Park Ave
1258 Monkey Dr
Daisy Johnson, 2468 Park Ave
Leo Fitz, 1258 Monkey Dr

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.