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
Python Program to Convert list of Dictionaries to Dictionary of Lists
In Python, a dictionary is a built-in data structure that stores data in key-value pairs. It allows efficient retrieval and modification of values based on their corresponding keys. Each key in a dictionary must be unique, and it is associated with a specific value.
A dictionary of lists is a dictionary where the values associated with each key are lists. This means that each key maps to multiple values, and those values are stored as elements within a list.
On the other hand, a list of dictionaries is a list that contains multiple dictionaries as its elements. Each dictionary within the list can have its own set of key-value pairs.
In this article, we will learn how to convert a list of dictionaries to a dictionary of lists in Python ?
Example
# Input: List of Dictionaries
list_of_dicts = [
{'cricketer': 'virat', 'score': 90},
{'cricketer': 'chahal', 'score': 30},
{'cricketer': 'dhoni', 'score': 120}
]
# Output: Dictionary of Lists
# {'cricketer': ['virat', 'chahal', 'dhoni'], 'score': [90, 30, 120]}
print(list_of_dicts)
[{'cricketer': 'virat', 'score': 90}, {'cricketer': 'chahal', 'score': 30}, {'cricketer': 'dhoni', 'score': 120}]
Methods Used
The following are the various methods used to accomplish this task:
Using Dictionary Comprehension
Using the for loop
Using pandas DataFrame
Using defaultdict
Using Dictionary Comprehension
Dictionary comprehension provides a concise way to create dictionaries by iterating over an existing sequence. For this conversion, we iterate through the keys of the first dictionary and collect corresponding values from all dictionaries ?
# Input list of dictionaries
data = [
{'cricketer': 'virat', 'score': 90},
{'cricketer': 'chahal', 'score': 30},
{'cricketer': 'dhoni', 'score': 120},
{'cricketer': 'pandya', 'score': 110},
{'cricketer': 'smith', 'score': 115}
]
# Using dictionary comprehension
result = {key: [d[key] for d in data] for key in data[0]}
print(result)
{'cricketer': ['virat', 'chahal', 'dhoni', 'pandya', 'smith'], 'score': [90, 30, 120, 110, 115]}
Using the for Loop
This method creates an empty dictionary and iterates through each dictionary in the list, collecting values for each key ?
# Input list of dictionaries
data = [
{'cricketer': 'virat', 'score': 90},
{'cricketer': 'chahal', 'score': 30},
{'cricketer': 'dhoni', 'score': 120}
]
# Create empty dictionary to store results
result = {}
# Initialize keys with empty lists
for key in data[0].keys():
result[key] = []
# Collect values for each key
for d in data:
for key in d:
result[key].append(d[key])
print(result)
{'cricketer': ['virat', 'chahal', 'dhoni'], 'score': [90, 30, 120]}
Using pandas DataFrame
Pandas provides a convenient way to convert between these data structures using the to_dict() method with orient="list" ?
import pandas as pd
# Input list of dictionaries
data = [
{'cricketer': 'virat', 'score': 90},
{'cricketer': 'chahal', 'score': 30},
{'cricketer': 'dhoni', 'score': 120}
]
# Convert using pandas DataFrame
result = pd.DataFrame(data).to_dict(orient="list")
print(result)
{'cricketer': ['virat', 'chahal', 'dhoni'], 'score': [90, 30, 120]}
Using defaultdict
The defaultdict from collections module automatically creates empty lists for new keys, simplifying the conversion process ?
from collections import defaultdict
# Input list of dictionaries
data = [
{'cricketer': 'virat', 'score': 90},
{'cricketer': 'chahal', 'score': 30},
{'cricketer': 'dhoni', 'score': 120}
]
# Using defaultdict
result = defaultdict(list)
for d in data:
for key, value in d.items():
result[key].append(value)
# Convert to regular dictionary
result = dict(result)
print(result)
{'cricketer': ['virat', 'chahal', 'dhoni'], 'score': [90, 30, 120]}
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Dictionary Comprehension | High | Fast | Simple, concise code |
| For Loop | Medium | Fast | Complex transformations |
| Pandas DataFrame | High | Slower | Data analysis workflows |
| defaultdict | High | Fast | Dynamic key handling |
Conclusion
Converting a list of dictionaries to a dictionary of lists can be accomplished through multiple approaches. Dictionary comprehension offers the most concise solution, while pandas is ideal for data analysis contexts. Choose the method that best fits your specific requirements and coding style.
