Iterate through Dictionary with multiple values in Python

In this Python tutorial, you will learn about Python iterating through a dictionary with multiple values.

I was creating a user management application in Python; I needed a way to store the user information containing the user details, and for that, I used the dictionary. I used the for loop method to access the user with their information as multiple values.

In this tutorial, I have explained the for-loop method and three more approaches to iterating through a dictionary with multiple values.

Let’s begin,

Python Iterate Through Dictionary with Multiple Values

In Python, iterating through a dictionary with multiple values means a dictionary containing a key with multiple values; you need to iterate through the dictionary and access the key with multiple values.

Let me show you how a dictionary with multiple values appears.

student_marks = {
    "Sam": [90, 85, 75],
    "Quill": [80, 95, 88],
    "Kat": [70, 82, 92]
}

Look at the above code. A dictionary of student_marks contains the student’s name and a list of their marks in the different subjects.

So, using a similar type of dictionary, you will learn how to iterate through it and access multiple values using different methods.

Python Iterate Dictionary Using the For Loop

You can use the for loop to iterate through a dictionary with multiple values and perform some operation on it.

Let’s see how to do that with an example. Suppose you have a dictionary named employees_skills, which contains the employee’s name as the key and their list of skills as a list of values, as shown in the code below.

employee_skills = {
	'James': ['Python', 'JavaScript'],
	'Jimmy': ['Java', 'C++', 'C#']
}

As shown in the code below, you can use the for loop to iterate over the employee_skills and access the employee name with multiple values.

for employee_name, skills in employee_skills.items():
	print(f"{employee_name}: {', '.join(skills)}")
Python Iterate Dictionary Using the For Loop

Look at the output. The for loop accesses each employee and their skills (which are multiple values).

READ:  How to generate 10 digit random number in Python?

Let’s understand the code part; first, a dictionary named ’employee_skills’ contains the employee name as a key and their skills as multiple values for that specific key.

After that, iterate through the dictionary using the loop ‘for employee_name, skills in employee_skills.items():’, where the items() function is called on the dictionary to return the key-value pair as a tuple.

Then, use the string formatting “f” to print the employee name and the join() function to attach the user skills to their name.

As a result, you can see iterating through a dictionary with multiple values and then printing each employee with their multiple skills, like ‘James: Python, JavaScript Jimmy: Java, C++, C#’.

Iterate Through Dictionary Python with Index

You can also iterate through a dictionary with multiple values based on the index value. Again, you will need to use the for loop, but to access the dictionary items with index, you will use the function enumerate().

You know about the for loop and items() function, which allows you to access the dictionary key-value pair.

But maybe you don’t know about the enumerate() function; if not, the enumerate() function takes an iterable, such as a list, adds the counter to it, and returns the enumerate object. You can use this enumerate object in a for loop, like a list, dictionary, etc., to iterate over it.

Below is the syntax for using the enumerate() function.

enumerate(iterable, start=0)

Where,

  • Iterable: In Python, iterable objects are like tuples, lists, strings, or dictionaries.
  • start: It is used to specify the index for the counter within the enumerate object.
READ:  Merge Dictionaries in Python (8 different methods)

For example, retake dictionary employee_skills and use the for loop to iterate through and access the key with multiple values with index.

employee_skills = {
	'James': ['Python', 'JavaScript'],
	'Jimmy': ['Java', 'C++', 'C#']
}
for index, (key, value) in enumerate(employee_skills.items()):
	print(f"Index: {index}, Key: {key}, Value: {value}")
Iterate Through Dictionary Python with Index

Look at the output with the employee’s name and skills. The index is also included as 0 for the first key-value pair and 1 for the second key-value pair in the list.

Let’s understand the code part, or for index, (key, value) in enumerate(employee_skills.items()):, here, the employee_skills.items are wrapped under the enumerate() function to add the index.

The employee_skill.items() returns the dictionary’s key pair, which is then passed to the enumerate() function using the enumerate(employee_skills.items()).

The enumerate object contains three things: a counter, which is considered an index, a key and a value.

Finally, printing the accessed index, key and value using the print(f”Index: {index}, Key: {key}, Value: {value}”). As a result, Index: 0, Key: James, Value: [‘Python’, ‘JavaScript’] Index: 1, Key: Jimmy, Value: [‘Java’, ‘C++’, ‘C#’].

This is how to iterate it through the dictionary Python with Index.

Dictionary Python with Multiple Values Using Dictionary Comprehension

The dictionary comprehension is similar to list comprehension, allowing you to dynamically generate a dictionary by using the loop with curly braces {}.

For example, suppose you have a dictionary named ‘car_details’, where keys are card models, and values are car details such as colour, engine type, and year, as shown below.

car_details = {
    "Honda Civic": {
        "year": 2023,
        "color": "red",
        "engine": "1.5L Turbo"
    },
    "Toyota Corolla": {
        "year": 2022,
        "color": "blue",
        "engine": "1.8L Hybrid"
    },
    "Tesla Model 3": {
        "year": 2021,
        "color": "black",
        "engine": "Electric"
    }
}

Now, to iterate over the dictionary ‘car_details’ containing the key with multiple values, you can use the dictionary comprehension, as shown in the code below.

{print(f"The currency of {key} is {', '.join(values)}.") for key, values in car_details.items()}
Dictionary Python with Multiple Values Using Dictionary Comprehension

Look at the output, iterating through the dictionary ‘car_details’ containing keys with multiple values using the dictionary comprehension.

READ:  raw input function in Python

As a result, ‘The currency of Honda Civic is year, color, engine. The currency of Toyota Corolla is year, color, engine. The currency of Tesla Model 3 is year, color, engine’.

This is the same logic within { } that you have used in the above section, ‘Python Iterate Dictionary Using the For Loop’.

I hope that the above example helps you understand how to iterate through the dictionary containing multiple values.

Conclusion

In this Python tutorial, you learned how to iterate over a dictionary with multiple values using the for loop and dictionary comprehension.

Apart from this, you also learned how to iterate through the dictionary with an index. While doing all of these things, you also learned about the enumerate() method of Python

You may like to read: