Kodeclik Blog
How to add four lists into one dictionary in Python
Imagine you're developing a student management system for a school. You have four separate lists containing student information: i) Student IDs, ii) Student names, iii) Student grades and iv) Student attendance percentages You want to combine this information into a single dictionary for easier data management and retrieval. For instance you might want to index using the ID and retrieve the name, grade, and attendance percentage for that student. Let us see how to do so!
Basically we have the following four lists:
student_ids = [1001, 1002, 1003, 1004]
student_names = ["Alice", "Bob", "Charlie", "David"]
student_grades = [85, 92, 78, 95]
student_attendance = [95.5, 98.0, 88.5, 97.5]
and we are trying to create a dictionary merging all these data structures. Here are four different ways to combine these lists into a dictionary:
Method 1: Use the zip() and dict() functions
This method is the simplest as you can see from the code below:
student_dict = dict(zip(student_ids, zip(student_names, student_grades, student_attendance)))
print(student_dict)
This method uses two zip() functions to pair the student IDs with tuples containing the other information. The first zip() combines student IDs with the result of the second zip(), which groups names, grades, and attendance. The dict() function then converts this zipped structure into a dictionary. This approach is concise but may be less readable for complex data structures.
The output will be:
{1001: ('Alice', 85, 95.5),
1002: ('Bob', 92, 98.0),
1003: ('Charlie', 78, 88.5),
1004: ('David', 95, 97.5)}
as expected. Note that the student ID is the key and the rest of the attributes are packaged into a list as the value.
Method 2: Use a dictionary comprehension
This approach uses a dictionary comprehension to create a nested dictionary structure:
student_dict = {id: {"name": name, "grade": grade, "attendance": attendance}
for id, name, grade, attendance in zip(student_ids, student_names, student_grades, student_attendance)}
print(student_dict)
As can be seen from the code, it iterates over the zipped lists, creating a dictionary for each student with their ID as the key and a nested dictionary containing their name, grade, and attendance as the value. This method is more explicit and easier to read, making it clear what each piece of data represents in the resulting dictionary.
The output will be:
{1001: {'name': 'Alice', 'grade': 85, 'attendance': 95.5},
1002: {'name': 'Bob', 'grade': 92, 'attendance': 98.0},
1003: {'name': 'Charlie', 'grade': 78, 'attendance': 88.5},
1004: {'name': 'David', 'grade': 95, 'attendance': 97.5}}
Note that the output is different from the previous output because we are being explicit about what each value is (i.e., whether it is a name or grade or attendance value).
Method 3: Use a a for loop and enumerate()
This method uses a traditional for loop with enumerate() to iterate through the lists and build the dictionary. It's the most verbose approach but also the most straightforward to understand, especially for beginners.
student_dict = {}
for i, id in enumerate(student_ids):
student_dict[id] = {
"name": student_names[i],
"grade": student_grades[i],
"attendance": student_attendance[i]
}
print(student_dict)
In the above code, the enumerate() function provides both the index and value of each student ID, which we use to access corresponding elements from the other lists. This method offers the most control over the dictionary creation process and is easily extensible.
The output is:
{1001: {'name': 'Alice', 'grade': 85, 'attendance': 95.5},
1002: {'name': 'Bob', 'grade': 92, 'attendance': 98.0},
1003: {'name': 'Charlie', 'grade': 78, 'attendance': 88.5},
1004: {'name': 'David', 'grade': 95, 'attendance': 97.5}}
Method 4: Use defaultdict from collections
This approach uses defaultdict to simplify the dictionary creation process, allowing for easy assignment of nested dictionaries.
from collections import defaultdict
student_dict = defaultdict(dict)
for id, name, grade, attendance in zip(student_ids, student_names, student_grades, student_attendance):
student_dict[id] = {"name": name, "grade": grade, "attendance": attendance}
print(dict(student_dict))
In the above code, the defaultdict() function automatically creates a new empty dictionary for each new key, eliminating the need for explicit key checks. We then iterate over the zipped lists to populate the dictionary. This method combines the readability of the for loop approach with the efficiency of using specialized data structures. It's particularly useful when dealing with more complex nested structures or when you need to append data to existing dictionary entries. But notice that you need to import defaultdict as it is not a built-in data structure.
Each of these methods will produce a dictionary where the student IDs are the keys, and the values are nested dictionaries containing the student's name, grade, and attendance percentage. The choice of method depends on personal preference, readability, and specific requirements of your project.
If you liked this blogpost, checkout our blogposts on how to update a Python dictionary, how to slice a Python dictionary, and even how to shuffle one!
Want to learn Python with us? Sign up for 1:1 or small group classes.