Python字典列表排序
import operator
x = [{'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]
sorted_x = sorted(x, key=operator.itemgetter('name'), reverse=True)
print sorted_x
# django
earns_stats = Callback.objects \
.filter(time__gte=query_date['s'], time__lte=query_date['e']) \
.extra({'order_time': "DATE(time)"}) \
.values('order_time', 'ad_source') \
.annotate(dcount=Count('id'), dsum=Sum('points'))
ad = ['total', 'youmi', 'duomob', 'chukong', 'midi', 'dianle', 'escore', 'anwo']
ad_id = [-1, 1, 11, 7, 5, 8, 9, 6]
tmp = {}
total = {}.fromkeys(ad)
for e in earns_stats:
# 所有数据统计
if not total['total']:
total['total'] = {
'down': e['dcount'],
'earns': e['dsum'],
}
else:
total['total']['down'] += e['dcount']
total['total']['earns'] += e['dsum']
# 每天数据统计
tmp.setdefault(e['order_time'], {}.fromkeys(ad))
if not tmp[e['order_time']]['total']:
tmp[e['order_time']]['total'] = {
'down': e['dcount'],
'earns': e['dsum'],
}
else:
tmp[e['order_time']]['total']['down'] += e['dcount']
tmp[e['order_time']]['total']['earns'] += e['dsum']
if e['ad_source'] in ad_id:
# 每天数据统计
tmp[e['order_time']][ad[ad_id.index(e['ad_source'])]] = {
'down': e['dcount'],
'earns': e['dsum'],
}
# 所有数据统计
if not total[ad[ad_id.index(e['ad_source'])]]:
total[ad[ad_id.index(e['ad_source'])]] = {
'down': e['dcount'],
'earns': e['dsum'],
}
else:
total[ad[ad_id.index(e['ad_source'])]]['down'] += e['dcount']
total[ad[ad_id.index(e['ad_source'])]]['earns'] += e['dsum']
datas = []
for t in tmp:
for a in tmp[t]:
if not tmp[t][a]:
tmp[t][a] = dict(down=0, earns=0)
tmp[t].setdefault('time', t)
datas.append(tmp[t])
datas = sorted(datas, key=operator.itemgetter('time'), reverse=True)
码字很辛苦,转载请注明来自ChenJiehua的《Python字典列表排序》
2014-07-17 2015-10-01 python

评论