How to iterate through a dictionary in Python

Feb 13, 2024#python

In Python, a dictionary is a mutable, unordered collection of key-value pairs. It is defined using curly braces {} and consists of keys and their associated values. You can use dictionaries for various purposes, such as storing and retrieving data in a structured way, representing configurations, or mapping relationships between entities.

d = {"name": "John", "age": 25, "city": "New York"}

# Access value using square brackets
print(d["name"])  # John

# Access value using get() method
# This method provides safer access and handles non-existent keys gracefully. 
# It takes the key and an optional default value as arguments.
print(d.get("non_existent_key"))  # None (default)
print(d.get("city", "Default Name"))  # New York

Key features of dictionaries in Python:

  • Unordered: The order of elements in a dictionary is not guaranteed. However starting from Python 3.7, dictionaries maintain the insertion order, but this behavior was officially guaranteed only from Python 3.7 onward.
  • Mutable: You can add, modify, or remove key-value pairs after dictionary has been created.
  • Keys are unique: Each key in a dictionary must be unique, but the values can be duplicated.

Iterating through a dictionary in Python involves accessing its keys and values individually or together. Here are three common methods:

Iterating through keys

To iterate through the keys of a dictionary, you can use the built-in .keys() method, which returns a view object that displays a list of all the keys. You can also use a for loop to loop over the dictionary directly, as it is equivalent to looping over its keys.

# Using .keys()
d = {"a": 1, "b": 2, "c": 3}
for k in d.keys():
    print(k)

# Using a for loop
d = {"a": 1, "b": 2, "c": 3}
for k in d:
    print(k)

Both of these loops will produce the same output, iterating through the keys of the dictionary and allowing you to access the corresponding values. The .keys() method can be useful when you want to be explicit about iterating through the keys, but using a for loop directly on the dictionary is a common and concise approach.

Iterating through values

To iterate through the values of a dictionary, you can use the built-in .values() method, which returns a view object that displays a list of all the values.

d = {"a": 1, "b": 2, "c": 3}
for v in d.values():
    print(v)

It’s important to note that the .values() method does not return a list but rather a view object that displays a list-like view of the dictionary’s values. This view object behaves similarly to a list in many situations, but it’s not an actual list.

If you explicitly need a list of values, you can convert the view object to a list using the list constructor:

d = {"a": 1, "b": 2, "c": 3}
values_list = list(d.values())

Iterating through key-value pairs

To iterate through the key-value pairs of a dictionary, you can use the built-in .items() method, which returns a view object that displays a list of tuples containing the key and value for each item.

d = {"a": 1, "b": 2, "c": 3}
for k, v in d.items():
    print(k, v)

Modifying the dictionary while iterating over it using keys can lead to unexpected behavior. It’s generally recommended to create a copy of the keys or use a different loop if modification is necessary.