usr bin env python coding utf-8 import datetime from itertools import

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python
# coding: utf-8
import datetime
from itertools import groupby
dicts=[
{'date': '2014-06-30', "obj_id": 1, 'value': 4, 'total': True},
{'date': '2014-07-01', "obj_id": 1, 'value': 1},
{'date': '2014-07-02', "obj_id": 1, 'value': 3},
{'date': '2014-06-30', "obj_id": 2, 'value': 6, 'total': True},
{'date': '2014-07-01', "obj_id": 2, 'value': 4},
{'date': '2014-07-02', "obj_id": 2, 'value': 2},
{'date': '2014-06-30', "obj_id": 3, 'value': 7, 'total': True},
{'date': '2014-07-01', "obj_id": 3, 'value': 5},
{'date': '2014-07-02', "obj_id": 3, 'value': 2},
]
res = []
for key,group in groupby(dicts, lambda x: x['obj_id']):
tmp = {}
data = []
tmp['obj_id'] = key
tmp['total'] = 0
for x in group:
total = x.get('total', False)
if total:
tmp['total'] = x['value']
continue
data.append(x)
# here sort data by datatime
# надеюсь дату можно так сравнимать?
data.sort(key=lambda x: datetime.datetime.strptime(x['date'], '%Y-%m-%d') )
tmp['data'] = data
res.append(tmp)
for x in res:
print 'obj_id',x['obj_id']
for y in x['data']:
print y['value'], y['date']
print 'total', x['total'],'\n \n'
# res
obj_id 1
1 2014-07-01
3 2014-07-02
total 4
obj_id 2
4 2014-07-01
2 2014-07-02
total 6
obj_id 3
5 2014-07-01
2 2014-07-02
total 7