I'm writing an API endpoint in Django Rest framework and want to make data for showing graph I have data like this which I get from the database.
data = [
{
"name": "Test 3",
"status": "Active",
"count": 1
},
{
"name": "Test 2",
"status": "Failed",
"count": 1
},
{
"name": "Test",
"status": "In Progress",
"count": 85
},
{
"name": "Test",
"status": "Failed",
"count": 40
},
{
"name": "Test",
"status": "Active",
"count": 1
},
{
"name": "Test",
"status": "Success",
"count": 218
},
{
"name": "Test 2",
"status": "Active",
"count": 1
}]
and I want to make final graph data from above like this in order to show it in the graph.
[
"labels": ['Test', 'Test 2', 'Test 3'],
"data": [
{
name: 'Active',
data: [1, 1, 1]
},
{
name: 'Failed',
data: [40, 1, 0]
},
{
name: 'Success',
data: [218, 0, 0]
},
{
name: 'In Progress',
data: [85, 0, 0]
}
]
]
I'm trying to make data in that way but I'm unable to make the correct format of data can anyone please help is there any built-in functions that I can use to make the data correct.
response = [
{
'labels': [],
'data':[],
}
]
for row in data:
if row['name'] not in response[0]['labels']:
response[0]['labels'].append(row['name'])
innerData = []
for status in ['Active', 'Failed', 'Success', 'In Progress']:
if status in row['status']:
innerData.append(row['count'])
else:
innerData.append(0)
response[0]['data'].append(
{
'name': status,
'data': innerData,
}
)
CodePudding user response:
In order to get unique labels, set comprehension
can be used. Then you can use defaultdict
to from key:value
pair as each status being key name and count being corresponding values.
from collections import defaultdict
data = [{"name": "Test 3", "status": "Active", "count": 1}, {"name": "Test 2", "status": "Failed", "count": 1}, {"name": "Test", "status": "In Progress", "count": 85},{"name": "Test", "status": "Failed", "count": 40},{"name": "Test", "status": "Active", "count": 1},{"name": "Test", "status": "Success", "count": 218}, {"name": "Test 2", "status": "Active", "count": 1}]
d = defaultdict(list)
labels = sorted({each['name'] for each in data})
for each in data:
d[each['status']].append(each['count'])
# -> defaultdict(<class 'list'>, {'Active': [1, 1, 1], 'Failed': [1, 40], 'In Progress': [85], 'Success': [218]})
final_result = {'labels': labels, 'data': []}
for k, v in d.items():
final_result['data'].append({'name': k, 'data': v})
final_result
would look like:
{'labels': ['Test', 'Test 2', 'Test 3'], 'data': [{'name': 'Active', 'data': [1, 1, 1]}, {'name': 'Failed', 'data': [1, 40]}, {'name': 'In Progress', 'data': [85]}, {'name': 'Success', 'data': [218]}]}
In order to fill small sized lists with zeros, refer to this answer.