Five Ways to Loop Through Python Dictionaries

Five Ways to Loop Through Python Dictionaries

Learning how to iterate over data is a critical skill in any programming language

Image for postPhoto by Pisit Heng on Unsplash

If you have used other languages in the past, surely you are acquainted with control structures that look like this:

while(i < 10) { // do stuff i = i + 1;}for(var i=0; i<10; i++) { // do stuff}

Python has its own flavor of loops, but simply adopting the same old structures in Python is really selling the language short.

Here are five different ways to write a for loop in Python, starting with a conversion of the traditional method.

1. Traditional For Loop

A traditional for loop has three components to its structure:

  • Variable initialization.
  • Comparison expression.
  • End expression.

Generally, this means you set an index to zero, compare it in an expression, and increment by one. To recreate this in Python, you would actually use a while loop but we can mimic the idea of an incrementing variable used to reference an index.

This method will not work for a dictionary because the data requires an iterable with positional values, but I wanted to include it for reference.

mock_data = [90, 45, 32, 44]for i in range(len(data)): print(data[i]) # 90, 45, 32, 44

2. No Method

Okay, on to dictionaries. Let?s start with the simplest method of writing a Python for loop.

mock_data = { “id”: 1, “first_name”: “Cory”, “last_name”: “Schimmang”, “email”: “[email protected]”, “gender”: “Female”, “ip_address”: “186.239.104.33”}for x in mock_data: print(x) # id, first_name, last_name, email, gender, ip_address “”” id first_name last_name email gender ip_address “””

The variable x will be assigned each iterable within mock_data. This method is akin to foreach loops in languages such as PHP.

Each key is stored to x and could be used to reference the value by printing mock_data[x] in our example.

3. Using .keys()

Another method of iterating over the keys in a dictionary is to use the .keys() method which returns a dict_keys object that is then iterated over as we store each value in our x variable.

mock_data = { “id”: 1, “first_name”: “Cory”, “last_name”: “Schimmang”, “email”: “[email protected]”, “gender”: “Female”, “ip_address”: “186.239.104.33”}for x in mock_data.keys(): print(x) “”” id first_name last_name email gender ip_address “””

4. Using .values()

If we want to get right at each value in the dictionary, then using the .values() method will store the term?s value in x rather than the key.

mock_data = { “id”: 1, “first_name”: “Cory”, “last_name”: “Schimmang”, “email”: “[email protected]”, “gender”: “Female”, “ip_address”: “186.239.104.33”}for x in mock_data.values(): print(x) “”” 1 Cory Schimmang [email protected] Female 186.239.104.33 “””

5. Using .items()

More often than not, you will want access to both the key and the value. In this scenario, use the .items() method, which returns each key-value pair as a two-value tuple.

To pre-split the tuple, specify two variables in your for loop so that the first tuple value (the key) and the second (the value) are stored in the first and second variables respectively.

mock_data = { “id”: 1, “first_name”: “Cory”, “last_name”: “Schimmang”, “email”: “[email protected]”, “gender”: “Female”, “ip_address”: “186.239.104.33”}for x in mock_data.items(): print(x) “”” (‘id’, 1) (‘first_name’, ‘Cory’) (‘last_name’, ‘Schimmang’) (’email’, ‘[email protected]’) (‘gender’, ‘Female’) (‘ip_address’, ‘186.239.104.33’) “””for k,v in mock_data.items(): print(k,v) “”” id 1 first_name Cory last_name Schimmang email [email protected] gender Female ip_address 186.239.104.33 “””

Conclusion

I hope you?ve learned a new technique for leveraging for loops in Python.

There are many methods available, each with their own pros and cons. Once you get into larger executions you may find performance differences, however, especially at a beginner?s level, try to iterate intentionally over what is necessary.

24