Dictionary Traversal: Methods to Iterate Over Keys, Values, and Key-Value Pairs in Python Dictionaries

In Python, a dictionary is a data structure used to store key-value pairs, such as {'name': 'Xiaoming', 'age': 18}. When we need to use the data in a dictionary, we often need to “traverse” its elements—meaning to access each key, value, or key-value pair one by one. This article will detail three common traversal methods for Python dictionaries, helping you quickly master how to handle dictionary data.

1. Traversing Dictionary Keys

The default way to traverse a dictionary is by iterating over its keys. If you directly use a for loop to traverse a dictionary, you will get each key in the dictionary.

Example Code:

person = {
    'name': 'Xiaoming',
    'age': 18,
    'gender': 'Male',
    'hobby': 'Programming'
}

# Traverse keys
for key in person:
    print(key)

Output:

name
age
gender
hobby

Explanation:
- for key in person will sequentially extract each key from the dictionary and assign it to the variable key.
- This method is the simplest and suitable for scenarios where only the “keys” are needed (e.g., counting the number of keys).

2. Traversing Dictionary Values

If you only need to retrieve the values from the dictionary, use the dict.values() method. dict.values() returns a “view object” containing all values (similar to a list but not a list itself; it can be traversed like a list).

Example Code:

# Traverse values
for value in person.values():
    print(value)

Output:

Xiaoming
18
Male
Programming

Note:
- Do not directly write for value in person, as this will traverse the keys (just like the previous example), not the values. You must explicitly use the values() method.
- If you need to convert the values into a list, you can use list(person.values()), but traversing the view object is usually sufficient.

3. Traversing Key-Value Pairs

If you need to obtain both each key and its corresponding value simultaneously, use the dict.items() method. dict.items() returns a view object containing tuples of all “key-value” pairs, where each tuple is in the form (key, value).

Example Code:

# Traverse key-value pairs
for key, value in person.items():
    print(f"{key}: {value}")

Output:

name: Xiaoming
age: 18
gender: Male
hobby: Programming

Explanation:
- for key, value will simultaneously receive the two elements in the tuple, allowing you to use both the key and the value in the loop (e.g., modifying the corresponding value based on the key).
- This method is the most commonly used, such as when generating reports or statistics that require both keys and values.

Precautions

  1. Order Consideration: In Python 3.7+, dictionaries maintain insertion order, so the traversal order is consistent with the insertion order of the keys. This is important if you need a strict order.
  2. Avoid Modifying the Dictionary: Do not directly modify the dictionary (e.g., adding/deleting key-value pairs) during traversal, as this may cause abnormal traversal results.
  3. Placeholder Usage: If you only need the value or key and not the other, use the underscore _ as a placeholder (e.g., for _, value in person.items() to ignore the key and only access the value).

Summary

There are three main ways to traverse Python dictionaries:
- Traverse keys: for key in dict
- Traverse values: for value in dict.values()
- Traverse key-value pairs: for key, value in dict.items()

Choose the appropriate method based on your needs, and you can easily handle dictionary data!

Xiaoye