Loop Through a Dictionary

Dictionaries in Python allow you to store data in key-value pairs. Looping through a dictionary is a common operation, and Python provides multiple ways to iterate over the keys, values, or both keys and values simultaneously.

Looping Through Keys:

When you loop through a dictionary without using any methods, you are iterating over its keys by default. This allows you to access the keys directly.

Python
person = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Loop through keys
for key in person:
    print(key)

# Output:
# name
# age
# city

If you only need to work with the keys, this method is straightforward and efficient.

Looping Through Values:

To loop through the values of a dictionary, you can use the values() method, which returns an iterable view of the dictionary's values.

Python
# Loop through values
for value in person.values():
    print(value)

# Output:
# John
# 30
# New York

This method is useful when you need to access or process the values without needing the keys.

Looping Through Keys and Values:

To loop through both keys and values at the same time, you can use the items() method. This method returns an iterable view of the dictionary's key-value pairs as tuples.

Python
# Loop through keys and values
for key, value in person.items():
    print(f"{key}: {value}")

# Output:
# name: John
# age: 30
# city: New York

This method is the most versatile as it allows you to work with both keys and values simultaneously.

Practical Example: Counting Word Frequencies

Let's use what we"ve learned to count the frequency of each word in a sentence. This example demonstrates the power of looping through a dictionary:

Python
sentence = "the quick brown fox jumps over the lazy dog the quick fox"
words = sentence.split()

# Create a dictionary to store word frequencies
word_count = {}

# Loop through each word in the sentence
for word in words:
    if word in word_count:
        word_count[word] += 1
    else:
        word_count[word] = 1

# Display word frequencies
for word, count in word_count.items():
    print(f"{word}: {count}")

# Output:
# the: 3
# quick: 2
# brown: 1
# fox: 2
# jumps: 1
# over: 1
# lazy: 1
# dog: 1

This example shows how you can use a dictionary to count the occurrences of each word in a string, demonstrating how looping through a dictionary can be applied in real-world scenarios.