'Split list of dictionaries into multiple list of dictionaries by its value in python
I wanted to split a list of dictionaries into multiple list of dictionaries based on the value of a particular key dynamically.
Actual_list = [{status:Pass,name:abc,loop_count:1},{status:Fail,name:abc,loop_count:1},{status:Fail,name:abc,loop_count:2},{status:Fail,name:abc,loop_count:2},]
Here the list of dictionaries holds values, which has to be split according to the key-value of loop_count. Each splitter list of dictionaries should hold unique value of loop_count
Expected_list =[ [{status:Pass,name:abc,loop_count:1}, {status:Fail,name:abc,loop_count:2}],[{status:Fail,name:abc,loop_count:1},{status:Fail,name:abc,loop_count:2}]]
Solution 1:[1]
IIUC:
from itertools import groupby
Actual_list = [
{"status": "Pass", "name": "abc", "loop_count": 1},
{"status": "Pass", "name": "abc", "loop_count": 1},
{"status": "Fail", "name": "abc", "loop_count": 1},
{"status": "Fail", "name": "abc", "loop_count": 2},
{"status": "Fail", "name": "abc", "loop_count": 2},
]
nums, vals = [], {}
for k, g in groupby(
sorted(Actual_list, key=lambda k: k["loop_count"]),
lambda k: k["loop_count"],
):
vals[k] = list(g)
nums.append(k)
out = []
while any(vals.values()):
out.append([vals[n].pop(0) for n in nums if vals[n]])
print(out)
Prints:
[
[
{"status": "Pass", "name": "abc", "loop_count": 1},
{"status": "Fail", "name": "abc", "loop_count": 2},
],
[
{"status": "Pass", "name": "abc", "loop_count": 1},
{"status": "Fail", "name": "abc", "loop_count": 2},
],
[{"status": "Fail", "name": "abc", "loop_count": 1}],
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrej Kesely |
