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

ListOfDictionaries = [
	{'cricketer': 'virat', 'score': 90},
	{'cricketer': 'chahal', 'score': 30},
	{'cricketer': 'dhoni', 'score': 120},
	{'cricketer': 'pandya', 'score': 110},
	{'cricketer': 'smith', 'score': 115}

]
DictionaryofLists: {'cricketer': ['virat', 'chahal', 'dhoni', 'pandya', 'smith'], 'score': [90, 30, 120, 110, 115]}

Methods Used

The following are the various methods used to accomplish this task:

  • Using the for loop

  • Using Dictionary Comprehension

  • Using pandas DataFrame

  • Using NumPy Module

Method 1: Using the for loop

This method creates an empty dictionary called dictOflists to store the resulting dictionary of lists. It then iterates through each dictionary in the input list using a loop, extracting the 'cricketer' key as the dictionary's key and assigning the entire dictionary as its value. Finally, it displays the resulting dictionary of lists, where each cricketer is a key mapping to their respective dictionary of scores.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task –.

  • Create a variable to store the input list of dictionaries.

  • Create an empty dictionary for storing the resultant dictionary of sets.

  • Use the for loop, to traversing in the input list of dictionaries for converting the input list of dictionaries to the dictionary of lists.

  • Display the output dictionary of lists.

Example

The following program converts the list of dictionaries to dictionary of lists using the for loop –

# input list of dictionaries
inputListOfDicts = [
	{'cricketer': 'virat', 'scores': [40, 70, 90]},
	{'cricketer': 'chahal', 'scores': [10, 25, 30]},
	{'cricketer': 'dhoni', 'scores': [35, 65, 120]},
	{'cricketer': 'pandya', 'scores': [58, 89, 110]},
	{'cricketer': 'smith', 'scores': [76, 110, 115]}

]

# creating an empty dictionary for 
# storing resultant dictionary of lists
dictOflists = {}

# traversing in the input list of dictionaries 
# for converting input list of dictionaries to a dictionary of lists
for i in inputListOfDicts:
  # Getting values
	cricketer = i['cricketer']
	dictOflists[cricketer] = i

# displaying the output dictionary of lists
dictOflists

Output

{'virat': {'cricketer': 'virat', 'scores': [40, 70, 90]},
 'chahal': {'cricketer': 'chahal', 'scores': [10, 25, 30]},
 'dhoni': {'cricketer': 'dhoni', 'scores': [35, 65, 120]},
 'pandya': {'cricketer': 'pandya', 'scores': [58, 89, 110]},
 'smith': {'cricketer': 'smith', 'scores': [76, 110, 115]}}

Method 2: Using Dictionary Comprehension

Dictionary comprehension in Python is a concise way to create dictionaries by iterating over an existing sequence or iterable, applying expressions or conditions to generate key-value pairs, resulting in compact and readable code. It allows for the creation of dictionaries in a single line, combining iteration and transformation.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task –.

  • Create a variable to store the input list of dictionaries.

  • Print the dictionary where the keys are the keys from the first dictionary in inputListOfDicts.

  • Print the values are lists of corresponding values from each dictionary in inputListOfDicts using list comprehension.

Example

The following program converts the list of dictionaries to dictionary of lists using dictionary comprehension –

# input list of dictionaries
inputListOfDicts = [
	{'cricketer': 'virat', 'score': 90},
	{'cricketer': 'chahal', 'score': 30},
	{'cricketer': 'dhoni', 'score': 120},
	{'cricketer': 'pandya', 'score': 110},
	{'cricketer': 'smith', 'score': 115}

]

# Using list comprehension
print({dict_key: [p[dict_key] for p in inputListOfDicts] for dict_key in inputListOfDicts[0]})

Output

{'cricketer': ['virat', 'chahal', 'dhoni', 'pandya', 'smith'], 'score': [90, 30, 120, 110, 115]}

Method 3: Using pandas DataFrame

In this method, we will convert a list of dictionaries into a dictionary of lists using a pandas dataframe.

Syntax

pandas.DataFrame(listofdictionary).to_dict(orient=”list”)

Parameters

  • listofdictionary: input list of dictionary.

  • to_dict() function: it converts into a dictionary

  • orient: converts into a list

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task –.

  • Use the import keyword to import the pandas module with an alias name.

  • Create a variable to store the input list of dictionaries.

  • Convert a list of dictionaries inputListOfDicts into a pandas DataFrame and then converts the DataFrame into a dictionary where the keys are the column names of the DataFrame, and the values are lists containing the values from each column.

Example

The following program converts the list of dictionaries to dictionary of lists using pandas dataframe

# importing pandas module
import pandas as pd


# input list of dictionaries
inputListOfDicts = [
    {"cricketer": "virat", "score": 90},
    {"cricketer": "chahal", "score": 30},
    {"cricketer": "dhoni", "score": 120},
    {"cricketer": "pandya", "score": 110},
    {"cricketer": "smith", "score": 115},
]

# converting into  dictionary of lists using pandas to_dict()
pd.DataFrame(inputListOfDicts).to_dict(orient="list")

Output

On executing, the above program will generate the following output –
{'cricketer': ['virat', 'chahal', 'dhoni', 'pandya', 'smith'],
 'score': [90, 30, 120, 110, 115]}

Method 4: Using NumPy Module

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task

  • Use the import keyword to import the numpy module with an alias name.

  • Use the array() function to create a numpy array.

  • Access first element of array value using indexing (starts from 0).

  • Print the result by using key as index.

The following program converts the list of dictionaries to dictionary of lists using the numpy module –

# importing numpy module with an alias name 
import numpy as np
 
# creating a numpy array using array() function 
inputArray = np.array([(25, 45), (30, 70)],
				dtype=[('num1', int),
					('num2', int)])
 

# accessing first array element using indexing
# (starts from 0)
print(inputArray[0])
 
# Printing by using key
print(inputArray['num1'])

Output

On executing, the above program will generate the following output –
(25, 45)
[25 30]

The code creates a NumPy array inputArray with specified data types and field names. It then demonstrates accessing elements of the array using indexing and key-based indexing.

Conclusion

In summary, this article examined four distinct techniques for converting a list of dictionaries into a dictionary of lists. The methods explored included traditional for loop iteration, concise dictionary comprehension, the utilization of pandas DataFrame, and the application of the NumPy module. Each approach has its own strengths and applicability based on specific needs and available resources.

Updated on: 17-Aug-2023

143 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements