![]() |
VOOZH | about |
We are given a list of dictionaries we need to convert it to dictionaries of lists. For example, we are given a list of dictionaries li = [{'manoj': 'java', 'bobby': 'python'}, {'manoj': 'php', 'bobby': 'java'}, {'manoj': 'cloud', 'bobby': 'big-data'}] we need to convert this to dictionary of list so that the output becomes {'manoj': ['java', 'php', 'cloud'], 'bobby': ['python', 'java', 'big-data']}.
Using Pandas, a list of dictionaries can be converted to a dictionary of lists by creating a DataFrame and utilizing the to_dict() method with orient='list'. This maps each key in the dictionaries to a list of its corresponding values.
{'manoj': ['java', 'php', 'cloud'], 'bobby': ['python', 'java', 'big-data']}
Explanation:
Table of Content
Defaultdictfrom Python's collections module is useful when we need to append to lists within a dictionary. It automatically initializes the dictionary keys with a default value in this case, an empty list, simplifying the process of appending data.
{'manoj': ['java', 'php', 'cloud'], 'bobby': ['python', 'java', 'big-data']}
Explanation:
This method uses dictionary comprehension to convert a list of dictionaries into a dictionary where each key maps to a list of values from the original dictionaries. The values for each key are collected across all dictionaries in the list.
{'manoj': ['java', 'php', 'cloud'], 'bobby': ['python', 'java', 'big-data']}
Explanation: dictionary comprehension iterates over each key in the first dictionary (li[0]) and for each key, it collects the corresponding values from all dictionaries in the list li into a list.
zip function can be efficiently used to convert alist of dictionaries into a dictionary of lists. In this approach, the values from each dictionary are grouped by keys and zip is used to transpose the list of values, so we can easily convert them into lists.
{'manoj': ['java', 'php', 'cloud'], 'bobby': ['python', 'java', 'big-data']}
Explanation: