Group List of Dictionary Data by Particular Key in Python
Last Updated :
29 Jan, 2025
Our task is to group the data based on a particular key across these dictionaries. This involves collecting all values associated with a specific key into a single group. For example, if we have a list of dictionaries like this: [{'id': 1, 'name': 'Alice', 'age': 25}, {'id': 2, 'name': 'Bob', 'age': 30}, {'id': 1, 'name': 'Charlie', 'age': 35}] and we want to group them by the 'id'
key then the output will be {1: [{'id': 1, 'name': 'Alice', 'age': 25}, {'id': 1, 'name': 'Charlie', 'age': 35}], 2: [{'id': 2, 'name': 'Bob', 'age': 30}]}.
Using a defaultdict
from the collections
module
defaultdict
allows us to automatically create an empty list for any key that doesn't exist and this makes it easier to group data without manually checking if the key exists.
Python
from collections import defaultdict
data = [{'id': 1, 'name': 'Aryan', 'age': 25}, {'id': 2, 'name': 'Harsh', 'age': 30}, {'id': 1, 'name': 'Kunal', 'age': 35}]
res = defaultdict(list)
for item in data:
res[item['id']].append(item)
print(dict(res))
Output{1: [{'id': 1, 'name': 'Aryan', 'age': 25}, {'id': 1, 'name': 'Kunal', 'age': 35}], 2: [{'id': 2, 'name': 'Harsh', 'age': 30}]}
Using itertools.groupby
itertools.groupby
can be used to group elements in a sorted list but it requires the list to be sorted by the key and that is why we sort the data first.
Python
from itertools import groupby
data = [{'id': 1, 'name': 'Aryan', 'age': 25}, {'id': 2, 'name': 'Harsh', 'age': 30}, {'id': 1, 'name': 'Kunal', 'age': 35}]
# Sorting the data by the 'id' key
data.sort(key=lambda x: x['id'])
# Using groupby to group the data by 'id'
res = {key: list(group) for key, group in groupby(data, key=lambda x: x['id'])}
print(res)
Output{1: [{'id': 1, 'name': 'Aryan', 'age': 25}, {'id': 1, 'name': 'Kunal', 'age': 35}], 2: [{'id': 2, 'name': 'Harsh', 'age': 30}]}
Explanation:
data.sort(key=lambda x: x['id'])
sorts the list of dictionaries based on the 'id'
key.groupby(data, key=lambda x: x['id'])
: then is used to group the sorted data by the 'id'
key.
Using a Regular Dictionary with a Loop
In this method we manually create a dictionary and append the dictionaries to the list of the corresponding key.
Python
data = [{'id': 1, 'name': 'Aryan', 'age': 25}, {'id': 2, 'name': 'Harsh', 'age': 30}, {'id': 1, 'name': 'Kunal', 'age': 35}]
res = {}
for item in data:
if item['id'] not in res:
res[item['id']] = []
res[item['id']].append(item)
print(res)
Output{1: [{'id': 1, 'name': 'Aryan', 'age': 25}, {'id': 1, 'name': 'Kunal', 'age': 35}], 2: [{'id': 2, 'name': 'Harsh', 'age': 30}]}
Explanation: for each item in data
we check if its 'id'
exists as a key in res and i
f not then we initialize it with an empty list, we then append each dictionary to the list corresponding to its 'id'
.
Similar Reads
Iterate over a dictionary in Python In this article, we will cover How to Iterate Through a Dictionary in Python. To Loop through values in a dictionary you can use built-in methods like values(), items() or even directly iterate over the dictionary to access values with keys.How to Loop Through a Dictionary in PythonThere are multipl
6 min read
Python - Keys associated with value list in dictionary Sometimes, while working with Python dictionaries, we can have a problem finding the key of a particular value in the value list. This problem is quite common and can have applications in many domains. Let us discuss certain ways in which we can Get Keys associated with Values in the Dictionary in P
4 min read
Dictionary with Tuple as Key in Python Dictionaries allow a wide range of key types, including tuples. Tuples, being immutable, are suitable for use as dictionary keys when storing compound data. For example, we may want to map coordinates (x, y) to a specific value or track unique combinations of values. Let's explores multiple ways to
4 min read
Ways to create a dictionary of Lists - Python A dictionary of lists is a type of dictionary where each value is a list. These dictionaries are commonly used when we need to associate multiple values with a single key.Initialize a Dictionary of ListsThis method involves manually defining a dictionary where each key is explicitly assigned a list
3 min read
Python - Convert list of dictionaries to JSON In this article, we will discuss how to convert a list of dictionaries to JSON in Python. Python Convert List of Dictionaries to JsonBelow are the ways by which we can convert a list of dictionaries to JSON in Python: Using json.dumps()Using json.dump()Using json.JSONEncoderUsing default ParameterDi
5 min read
Flatten given list of dictionaries - Python We are given a list of dictionaries, and the task is to combine all the key-value pairs into a single dictionary. For example, if we have: d = [{'a': 1}, {'b': 2}, {'c': 3}] then the output will be {'a': 1, 'b': 2, 'c': 3}Using the update() methodIn this method we process each dictionary in the list
3 min read
Interesting Facts About Python Dictionary Python dictionaries are one of the most versatile and powerful built-in data structures in Python. They allow us to store and manage data in a key-value format, making them incredibly useful for handling a variety of tasks, from simple lookups to complex data manipulation. There are some interesting
7 min read
How to Create a Dictionary in Python The task of creating a dictionary in Python involves storing key-value pairs in a structured and efficient manner, enabling quick lookups and modifications. A dictionary is an unordered, mutable data structure where each key must be unique and immutable, while values can be of any data type. For exa
3 min read
Get Key from Value in Dictionary - Python The goal is to find the keys that correspond to a particular value. Since dictionaries quickly retrieve values based on keys, there isn't a direct way to look up a key from a value. Using next() with a Generator ExpressionThis is the most efficient when we only need the first matching key. This meth
5 min read