Home Python How to iterate through a dictionary in Python

How to iterate through a dictionary in Python

Dictionaries are frequently used in our day in day out activities as developers. They allow us to store key, value pairs of data in an organized and presentable manner. They also enable us to access the data in constant time O(1).

Therefore, you must understand how to iterate over a dictionary if you intend to use it in one way or another during your development. If you don’t, then your experience with using dictionaries may turn out to be very daunting.

In Python, dictionaries are a form of collections. In comparison to lists, tuples, and sets, you store key-value pairs rather than individual values. This means that instead of using an index to refer to your values, you use a key, which is a one-of-a-kind identifier. To access either the keys or the values individually, you will need to iterate over the given dictionary. Thus, we will go through everything you need to know to master how to iterate through a dictionary in Python using diverse kinds of iterators while riding on the for loop.

A dictionary can be expressed as an unordered set of data values, similar to a map, used to store data values in Python. Unlike other data types, which only hold a single value as an element, a dictionary holds a key: value pair.

Iterating through a dictionary in Python

There are numerous approaches to iterate over a dictionary in Python. The main ones include:

  • Iterate through all of the keys.
  • Iterate over all of the values.
  • Iterate over all of the key-value pairs.

Use dict. items() to iterate over keys and values in a dictionary

Here, a for loop with two different variables will aid in iterating a dictionary through dict. items(). As a result, individual keys and values of the given dictionary can be accessed individually. The items() method of the dictionary object is responsible for returning a list of tuples, with every single tuple having a key and a value. Then every tuple is unpacked to two variables. Thus, you can print a single dictionary at a time. The latter approach assigns both the keys and the values simultaneously.

Example : How to use dict. items()

sample_dictionary = {"a": 1, "b": 2}

for key, value in sample_dictionary.items():
    print(key, value)

for item in sample_dictionary.items():
    print(item, end="")
Example 1: Use dict. items()
Example 1: Use dict. items()

Use dict. keys() to iterate over the keys in a dictionary

To iterate through dict. keys(), for loop, is used to access the individual keys in the specified dictionary.

Example 1: use dict. keys()

sample_dictionary = {"a": 1, "b": 2}

for key in sample_dictionary.keys():
    print(key)
Example 1: use dict. keys()
Example 1: use dict. keys()

Alternatively, use in keyword with the dictionary. What happens is the dictionary invokes the iter() method. Thus, the method will return an iterator that will implicitly go through all the keys given in the dictionary, as shown below.

Example 2: use dict. Keys()

sample_dictionary = {"a": 1, "b": 2}

for key in sample_dictionary:
    print(key, ':', key)
Example 2: use dict. Keys()
Example 2: use dict. Keys()

Alternatively, you may choose to fetch an associated value for every key in the keys() list, as shown below.

Example 3: use dict. Keys()

sample_dictionary = {"a": 1, "b": 2}
for k in sample_dictionary.keys():
	print (k, sample_dictionary[k])
Example 3: use dict. Keys()
Example 3: use dict. Keys()

Program that iterates over all the keys contained in a given dictionary in a specific order

from collections import OrderedDict

subjectsAndCodes = OrderedDict([
('English', 'ENG'),
('Mathematics', 'Math'),
('Religious Education', 'RE'),
('Biology', 'Bio')
])
					
print('List Of given subjects and their codes:\n')

# Iterating over keys
for subCode in subjectsAndCodes:
	print(subCode)
Program that iterates over all the keys contained in a given dictionary in a specific order
Program that iterates over all the keys contained in a given dictionary in a specific order

The keys and values in the above dictionary are stored in the order in which they were described in the dictionary. This makes it an OrderedDict. As a result, if we want to keep the order of (key, value) stored in the dictionary, we should use the above approach.

Use dict. values() to iterate over the values of a dictionary

For loop is used to iterate through dict. values()to access the individual values in a given dictionary. This approach is different from the others because it only provides values. Thus, use it when you are all about keys.

Example 1: Use dict. Values()

sample_dictionary = {"a": 1, "b": 2}

for value in sample_dictionary.values():
    print(value)
Example 1: Use dict. Values()
Example 1: Use dict. Values()

Example 2: Use dict. values()

sample_dictionary = {"a": 1, "b": 2}

for key in sample_dictionary:
    print(key, ':', sample_dictionary[key])
Example 2: Use dict. Values()
Example 2: Use dict. values()

Iteration in Sorted Order

In Python, you sometimes need to iterate through a dictionary in sorted order. This can be accomplished by using sorted data (). As a result, you have a list with the elements of iterable in sorted order when you call sorted(iterable).

Let’s look at how to use Python’s sorted() function to iterate through a dictionary in sorted order.

Keys have been used to sort the data.

If you want to iterate over a dictionary in Python and order it by keys, you can pass your dictionary as an argument to sorted (). This will return a list of keys in sorted order, which you can iterate through as shown below:

Example 1: Iteration in Sorted Order

car_mileage = {'Toyota': 260, 'Nissan': 680, 'Benz': 300}
for key in sorted(car_mileage ):
     print(key, '->', car_mileage [key])
Example 1: Iteration in Sorted Order
Example 1: Iteration in Sorted Order

Using sorted (car_mileage ) in the loop’s header, you sorted the dictionary (alphabetically) by keys in this example. Similar results can be achieved by using sorted (car_mileage . Keys ()) as shown below. In both cases, you’ll get a list of your dictionary’s keys in sorted order.

Example 2: Iteration in Sorted Order

car_mileage = {'Toyota': 260, 'Nissan': 680, 'Benz': 300}
sorted (car_mileage . keys ())
Example 2: Iteration in Sorted Order
Example 2: Iteration in Sorted Order

Note that the sorting order will be determined by the data type you use for keys and values, as well as the internal Python rules for sorting certain data types.

Values-based sorting

In Python, you would also need to iterate through a dictionary of items sorted by values. You may still use sorted(), but this time with the main statement.

The keyword argument defines a one-argument feature that extracts a comparison key from each element you’re processing.

Simply write a function returning the value of each object and use it as the main argument to sorted() to sort the items of a dictionary by values:

Example 1: Values-based sorting

car_mileage = {'Toyota': 260, 'Nissan': 680, 'Benz': 300}

def by_value(item):
 return item[1]

for key, val in sorted(car_mileage.items(), key=by_value):
 	print(key, '->', val)
Example 1: Values-based sorting
Example 1: Values-based sorting

In this example, we have defined by_value() and applied it to sort car_mileage items’ by value. Then you used sorted to iterate through the dictionary in sorted order (). sorted () is told to order incomes by the main function (by_value ()). items() returns the value of the second element of each object (item [1]).

You could also only iterate through the values of a dictionary in sorted order, ignoring the keys. In that case,.values() can be used as follows:

Example 2: Values-based sorting

car_mileage = {'Toyota': 260, 'Nissan': 680, 'Benz': 300}
for value in sorted(car_mileage.values()):
     print(value)
Example 2: Values-based sorting
Example 2: Values-based sorting

sorted(car_mileage.values()) returned the dictionary’s values in the order you specified. When you use car_mileage.values(), the keys aren’t available, but you don’t always need the keys; sometimes you need the values, which is a quick way to get them.

Sort Dictionaries in reverse order

You may use reverse=True as an argument to sort your dictionaries in reverse order (). A Boolean value should be passed to the keyword statement reverse. If it’s set to True, the elements will be sorted backward:

car_mileage = {'Toyota': 260, 'Nissan': 680, 'Benz': 300}
for key in sorted(car_mileage, reverse=True):
	print(key, '->', car_mileage [key])
Sort Dictionaries in reverse order
Sort Dictionaries in reverse order

You used sorted (car_mileage, reverse=True) in the header of the for loop to iterate through the keys of car_mileage in reverse order.

Finally, it’s worth noting that sorted () does not change the order of the underlying dictionary. What happens is that sorted () generates an independent list with its elements sorted in ascending order, so car_mileage remain constant.

car_mileage
car_mileage has remained constant.
car_mileage has remained constant

This code demonstrates that car_mileage has remained constant. car_mileage was not modified by sort (). It simply produced a new sorted list from the income keys.

Conclusion

Overall, dictionaries are a form of collections. In comparison to lists, tuples, and sets, you store key-value pairs rather than individual values. In this article, we covered the core approaches to iterating over a dictionary in Python. These comprise the dictionary methods values(), keys(), and items with the aid of a for a loop.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More