results
is a list of dict having panel name and work type and price to do that work on that panel. There can be two dicts for same name and work type where one of them is on car model level and another is on car type level. In such cases we would give preference to car model level dict.
output
is the group of panels and prices per work type (removing the prices on car type if car model price exist for same panel and work type combination).
results = sorted(results, key=lambda datum: datum['car_model'])
#removing the car type if car model exists.
d = defaultdict(dict)
for l in results:
d[l['name']+'-'+l['work_type']] = l
results = d.values()
#grouping the results at panel level.
d = defaultdict(dict)
for l in results:
d.setdefault(l['name'],[]).append(l)
#creating dict such that panel name is key and price_list is array of all the panel prices.
output = []
for key,value in d.iteritems():
output.append({"name":key,"price_list":value})
Example input:
results = [
{
"id":1,
"car_type":1,
"car_model":None,
"name":"Door",
"work_type":"Dent",
"price":2300,
},
{
"id":2,
"car_type":1,
"car_model":None,
"name":"Door",
"work_type":"Scratch",
"price":1200,
},
{
"id":3,
"car_type":None,
"car_model":2,
"name":"Door",
"work_type":"Dent",
"price":2500,
},
{
"id":4,
"car_type":1,
"car_model":None,
"name":"Fender",
"work_type":"Dent",
"price":2300,
},
{
"id":5,
"car_type":1,
"car_model":None,
"name":"Fender",
"work_type":"Scratch",
"price":1300,
}
]
Expected output:
[{'name': 'Fender',
'price_list': [{'car_model': None,
'car_type': 1,
'id': 5,
'name': 'Fender',
'price': 1300,
'work_type': 'Scratch'},
{'car_model': None,
'car_type': 1,
'id': 4,
'name': 'Fender',
'price': 2300,
'work_type': 'Dent'}]},
{'name': 'Door',
'price_list': [{'car_model': 2,
'car_type': None,
'id': 3,
'name': 'Door',
'price': 2500,
'work_type': 'Dent'},
{'car_model': None,
'car_type': 1,
'id': 2,
'name': 'Door',
'price': 1200,
'work_type': 'Scratch'}]}]
output
is expected output but I have removed few fields fromoutput
to make it short. Updated the question with correct output. \$\endgroup\$car_model
asNone
result in an error when doingresults = sorted(results, key=lambda datum: datum['car_model'])
? \$\endgroup\$