通过某个字段将记录分组

itertools.groupby()函数对于这样的分组非常实用

rows = [
    {'address': '5412 N CLARK', 'date': '07/01/2012'},
    {'address': '5148 N CLARK', 'date': '07/04/2012'},
    {'address': '5800 E 58TH', 'date': '07/02/2012'},
    {'address': '2122 N CLARK', 'date': '07/03/2012'},
    {'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'},
    {'address': '1060 W ADDISON', 'date': '07/02/2012'},
    {'address': '4801 N BROADWAY', 'date': '07/01/2012'},
    {'address': '1039 W GRANVILLE', 'date': '07/04/2012'},
]

想按照date分组后的数据进行跌代,先要对date进行排序。

from operator import itemgetter
from itertools import groupby

rows.sort(key=itemgetter('date'))#排序
for date,items in groupby(rows,key=itemgetter('date')):
    #date是groupby找的相同的元素,items是元素所在的那个字典
    print(date)
    for i in items:
        print(i)

结果:

07/01/2012
{'address': '5412 N CLARK', 'date': '07/01/2012'}
{'address': '4801 N BROADWAY', 'date': '07/01/2012'}
07/02/2012
{'address': '5800 E 58TH', 'date': '07/02/2012'}
{'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'}
{'address': '1060 W ADDISON', 'date': '07/02/2012'}
07/03/2012
{'address': '2122 N CLARK', 'date': '07/03/2012'}
07/04/2012
{'address': '5148 N CLARK', 'date': '07/04/2012'}
{'address': '1039 W GRANVILLE', 'date': '07/04/2012'}

 仅仅只是想根据 date 字段将数据分组到一个大的数据结构中去,并且允许随机访问, 那么最好使用 defaultdict() 来构建一个多值字典

from collections import defaultdict
row_date = defaultdict(list)
for row in rows:
    row_date[row['date']].append(row)
for r in row_date['07/04/2012']:
    print(r) ##{'address': '5148 N CLARK', 'date': '07/04/2012'}{'address': '1039 W GRANVILLE', 'date': '07/04/2012'}

 

posted @ 2022-07-01 13:59  花桥  阅读(22)  评论(0)    收藏  举报