Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert key-values list to flat dictionary in Python
When working with dictionaries that contain lists as values, you may need to convert them into a flat dictionary where elements from the lists become key-value pairs. Python provides several approaches to achieve this transformation.
Understanding the Problem
A key-values list dictionary has keys mapped to lists of values. Converting to a flat dictionary means pairing corresponding elements from these lists into key-value pairs.
Using zip() Method
The most common approach uses zip() to pair corresponding elements from two lists ?
my_dict = {'month_num': [1, 2, 3, 4, 5, 6], 'name_of_month': ['Jan', 'Feb', 'March', 'Apr', 'May', 'June']}
print("Original dictionary:")
print(my_dict)
flat_dict = dict(zip(my_dict['month_num'], my_dict['name_of_month']))
print("Flattened dictionary:")
print(flat_dict)
Original dictionary:
{'month_num': [1, 2, 3, 4, 5, 6], 'name_of_month': ['Jan', 'Feb', 'March', 'Apr', 'May', 'June']}
Flattened dictionary:
{1: 'Jan', 2: 'Feb', 3: 'March', 4: 'Apr', 5: 'May', 6: 'June'}
Using Dictionary Comprehension
Dictionary comprehension provides a more concise approach ?
data = {'keys': ['name', 'age', 'city'], 'values': ['Alice', 25, 'New York']}
print("Original data:")
print(data)
flat_dict = {k: v for k, v in zip(data['keys'], data['values'])}
print("Flattened dictionary:")
print(flat_dict)
Original data:
{'keys': ['name', 'age', 'city'], 'values': ['Alice', 25, 'New York']}
Flattened dictionary:
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Multiple Key-Value Pairs
When dealing with multiple key-value list pairs, you can combine them ?
data = {
'students': ['John', 'Sarah', 'Mike'],
'grades': [85, 92, 78],
'subjects': ['Math', 'Science', 'English']
}
print("Original data:")
print(data)
# Create student-grade mapping
student_grades = dict(zip(data['students'], data['grades']))
print("Student grades:", student_grades)
# Create student-subject mapping
student_subjects = dict(zip(data['students'], data['subjects']))
print("Student subjects:", student_subjects)
Original data:
{'students': ['John', 'Sarah', 'Mike'], 'grades': [85, 92, 78], 'subjects': ['Math', 'Science', 'English']}
Student grades: {'John': 85, 'Sarah': 92, 'Mike': 78}
Student subjects: {'John': 'Math', 'Sarah': 'Science', 'Mike': 'English'}
How It Works
The zip() function takes multiple iterables and returns an iterator of tuples, where each tuple contains elements from the input iterables at the same position. The dict() constructor converts these tuples into key-value pairs.
Conclusion
Use dict(zip()) to convert key-values list dictionaries into flat dictionaries. Dictionary comprehension with zip() provides a more readable alternative for complex transformations.
