Python循环使用相同的键

时间:2016-06-06 09:07:42

标签: python dictionary

我有这个:

aa =     [
     {'id_o': 14285, 'id': 253004, 'value1': '0', 'value2': 0.018406, 'date': u'2015-12-03', 'calc': -0.018406},
     {'id_o': 14285, 'id': 253004, 'value1': '0', 'value2': 0.043895, 'date': u'2015-12-04', 'calc': -0.043895},
     {'id_o': 14285, 'id': 253004, 'value1': '0', 'value2': 0.025996, 'date': u'2015-12-05', 'calc': -0.025996},
     {'id_o': 14285, 'id': 253004, 'value1': '0', 'value2': 0.034537, 'date': u'2015-12-06', 'calc': -0.034537},
     {'id_o': 14285, 'id': 253004, 'value1': '0', 'value2': 0.053107, 'date': u'2015-12-07', 'calc': -0.053107},
     {'id_o': 14285, 'id': 253004, 'value1': '0', 'value2': 0.060436, 'date': u'2015-12-08', 'calc': -0.060436},
     {'id_o': 14285, 'id': 253004, 'value1': '0', 'value2': 0.047265, 'date': u'2015-12-09', 'calc': -0.047265},
     {'id_o': 14285, 'id': 253007, 'value1': '0', 'value2': 0.075509, 'date': u'2015-12-03', 'calc': -0.075509},
     {'id_o': 14285, 'id': 253007, 'value1': '0', 'value2': 0.122235, 'date': u'2015-12-04', 'calc': -0.122235},
     {'id_o': 14285, 'id': 253007, 'value1': '0', 'value2': 0.096103, 'date': u'2015-12-05', 'calc': -0.096103},
     {'id_o': 14285, 'id': 253007, 'value1': '0', 'value2': 0.116113, 'date': u'2015-12-06', 'calc': -0.116113},
     {'id_o': 14285, 'id': 253007, 'value1': '0', 'value2': 0.112743, 'date': u'2015-12-07', 'calc': -0.112743},
     {'id_o': 14285, 'id': 253007, 'value1': '0', 'value2': 0.125755, 'date': u'2015-12-08', 'calc': -0.125755},
     {'id_o': 14285, 'id': 253007, 'value1': '0', 'value2': 0.126911, 'date': u'2015-12-09', 'calc': -0.126911}
    ]

我如何通过具有相同ID的dict进行循环?

我需要按ID

比较value1 value2和calc每天

我该怎么做?

由于

1 个答案:

答案 0 :(得分:2)

使用itertools.groupby轻松转换为词典:{id: [dict]}

from itertools import groupby
# from operator import itemgetter

key = lambda d: d['id']
# key = itemgetter('id')  
# mostly a matter of taste, but itemgetter is more performant in some contexts

id_dicts = {k: list(g) for k, g in groupby(sorted(aa, key=key), key=key)}

现在,你可以循环id:

for id in id_dicts:
    # do stuff
    for d in id_dicts[id]:
        # do stuff with d['value1'], d['value2'], etc.