Flow control

Looping through Dictionaries

1. Looping through Keys:

This approach focuses on iterating over all the keys present in the dictionary.

Syntax:

for key in dictionary_name:
    # Your code to process the key
    print(key)  # Example: Print each key

  • In this example, the loop variable key takes on the value of each key in the dictionary one at a time during each iteration.
  • You can then use key inside the loop to access the corresponding value using square brackets [] or the get() method.

2. Looping through values:

This method iterates over all the values stored in the dictionary.

Syntax:

for value in dictionary_name.values():
    # Your code to process the value
    print(value)  # Example: Print each value

  • Here, the loop variable value takes on the value of each value in the dictionary during each iteration.
  • You can use value to perform any operations you need on the values.

3. Looping through Key-Value Pairs:

This is the most common and versatile way to loop through dictionaries. It allows you to access both the key and the value simultaneously within the loop.

Syntax:

for key, value in dictionary_name.items():
    # Your code to process both key and value
    print(f"{key}: {value}")  # Example: Print each key-value pair

  • In this case, the loop unpacks each key-value pair from the dictionary into two variables: key and value.
  • This gives you the flexibility to use both the key and the value within the loop body.

Choosing the right looping method:

The choice of looping method depends on what you need to achieve:
  • If you only need to process the keys, use the for key in dictionary_name loop.
  • If you only need to process the values, use the for value in dictionary_name.values() loop.
  • If you need to work with both keys and values simultaneously, use the for key, value in dictionary_name.items() loop.

It's time to take a quiz!

Test your knowledge and see what you've just learned.

What will be the output of the following code? my_dict = {"a": 1, "b": 2, "c": 3} for key in my_dict: print(key)

a b c
1 2 3
{"a": 1, "b": 2, "c": 3}
None
Check Answer

How can you print all values in the following dictionary? my_dict = {"a": 1, "b": 2, "c": 3} # Your code here

for value in my_dict.values(): print(value)
for value in my_dict: print(value)
print(my_dict)
print(my_dict.values())
Check Answer

What does the following code print? my_dict = {"a": 1, "b": 2, "c": 3} for key, value in my_dict.items(): print(f"{key}: {value}")

a: 1 b: 2 c: 3
1: a 2: b 3: c
{"a": 1, "b": 2, "c": 3}
None
Check Answer

When should you use the following loop? for value in dictionary_name.values():

When you only need to process values.
When you only need to process keys.
When you need to process both keys and values.
When you want to modify the dictionary.
Check Answer