How to Iterate through a Dictionary in Python

There are several methods for iterating through dictionary keys and values, each with its own advantages and use cases.

  • Loop directly over the dictionary: to access the keys in their insertion order.
  • Use the keys() method: to iterate over all the keys in the dictionary.
  • Use the values() method: if you need to work with the values.
  • Use the items() method: for iterating through key-value pairs.
  • Use enumerate() with items(): if you need the index along with the key-value pairs.
  • Use generator expressions: for memory-efficient filtering and iteration.
  • Use filter() with the items() method: to selectively iterate based on conditions.
  • Iterate over sorted keys or values: for sorted iteration.

Understanding these methods is crucial for effectively working with dictionaries. So let’s explore these methods in detail:

Looping Directly Over the Dictionary

When you use a for loop directly on a dictionary, it iterates over the keys of the dictionary. This is the simplest way to iterate over keys.

D = {'name': 'Bob', 'age': 25, 'job': 'Dev'}

for x in D:
    print(x)
# Output: name age job

To iterate over the values of a dictionary, you can easily access each value by using its corresponding key as follows:

D = {'name': 'Bob', 'age': 25, 'job': 'Dev'}

for x in D:
    print(D[x])
# Output: Bob 25 Dev

Using keys() Method

The keys() method returns a list of keys from a dictionary and is generally used to iterate over all the keys in the dictionary.

D = {'name': 'Bob', 'age': 25, 'job': 'Dev'}

for x in D.keys():
    print(x)
# Output: name age job

Please note that the object returned by keys() is a view object, not a list or a static collection of keys. This means it provides a dynamic view on the dictionary’s keys; therefore, if you add or remove keys from the dictionary, the view will change accordingly.

This is particularly useful for iterating over keys while modifying the dictionary.

D = {'name': 'Bob', 'age': 25}

# Assign dict keys to V
V = D.keys()

# Add an entry to dict D
D['job'] = 'Dev'

# V reflects changes done to dict D
print(V)
# Output: dict_keys(['name', 'age', 'job'])

Using values() Method

The values() method returns a list of values from a dictionary and is generally used to iterate over all the values in the dictionary.

D = {'name': 'Bob', 'age': 25, 'job': 'Dev'}

for x in D.values():
    print(x)
# Output: Bob 25 Dev

Similar to keys(), the object returned by values() is a view object; therefore, if you add or remove values from the dictionary, the view will change accordingly.

D = {'name': 'Bob', 'age': 25}

# Assign dict values to V
V = D.values()

# modify dict D
D['name'] = 'Sam'

# V reflects changes done to dict D
print(V)
# Output: dict_values([25, 'Sam'])

Please note that this method does not provide access to the keys, so it is only suitable when the values are what you’re interested in.

Using items() Method

The items() method returns a list of tuples containing the key:value pairs of the dictionary. The first item in each tuple is the key, and the second is its associated value.

This method offers the most comprehensive way to iterate through a dictionary, as it provides simultaneous access to both keys and values.

D = {'name': 'Bob', 'age': 25}

for x in D.items():
    print(x)

# Output:
# ('age', 25)
# ('name', 'Bob')

Similar to keys() and values(), the object returned by items() is a view object; therefore, if you add or remove entries from the dictionary, the view will change accordingly.

Using enumerate() with items()

Although not commonly used with dictionaries, if you need both the index and the key-value pairs, you can use the enumerate() function.

The enumerate() function basically adds an index counter to an iterable, allowing you to access both the index and the element during each iteration. By combining it with the items() method, you can obtain both the index and the key:value pair.

# print the index, key, and value for each item in dictionary D
D = {'name': 'Bob', 'age': 25, 'job': 'Dev'}
for index, item in enumerate(D.items()):
    key, value = item
    print(f"Index: {index}, Key: {key}, Value: {value}")

# Output:
# Index: 0, Key: name, Value: Bob
# Index: 1, Key: age, Value: 25
# Index: 2, Key: job, Value: Dev

Iterating Using Generator Expressions

Generator expressions allow you to iterate over dictionary items lazily, which means items are generated one at a time and only when needed. This can be especially useful for large dictionaries where memory efficiency is a concern.

For example, the code below iterates over and prints key:value pairs from dictionary D where values are greater than 1.

D = {'a': 1, 'b': 2, 'c': 3}
gen = ((key, value) for key, value in D.items() if value > 1)
for item in gen:
    print(item)

# Output:
# ('b', 2)
# ('c', 3)

This method is beneficial when you want to apply a condition to the items you’re iterating over.

Using filter() to Iterate Over Certain Items

Similar to the previous method, the filter() function can be used to iterate over items that meet a certain condition.

The code below iterates over and prints key:value pairs from dictionary D where values are greater than 1.

D = {'a': 1, 'b': 2, 'c': 3}
filtered_items = filter(lambda item: item[1] > 1, D.items())
for item in filtered_items:
    print(item)

# Output:
# ('b', 2)
# ('c', 3)

Iterating Over Sorted Keys or Values

Iterating over a dictionary in Python typically happens in insertion order, not necessarily in the order the keys were defined. However, if you need to iterate through the keys or values in a sorted order, the sorted() function comes in handy.

The code below sorts the dictionary keys alphabetically, then iterates through these sorted keys to print each key along with its corresponding value.

# Iterating over items sorted by key
D = {'y': 2, 'x': 3, 'z': 1}

for key in sorted(D.keys()):
    print(key, D[key])

# Output:
# x 3
# y 2
# z 1

If you wish to iterate through values in a sorted order, you can utilize custom sorting criteria (by using the key argument) in the sorted() function. To be more specific, the dictionary’s get() method, which retrieves the value associated with a given key, is used as the sorting criteria.

# Iterating over items sorted by value
D = {'y': 2, 'x': 3, 'z': 1}

for key in sorted(D, key=D.get):
    print(key, D[key])

# Output:
# z 1
# y 2
# x 3