The method of the same value python key packet

method one:

Use itertools.groupby ()

rows = [
     {'address': '5412 N CLARK ', 'date ': '07/12/2012 ’ }, 
     {'address': '5148 N CLARK ', 'date ’: '07/04/2012 ’ }, 
     {'address': '5800 E 58TH ’, 'date ’: '07 /12/2012 ’ },   
]
from operator import itemgetter
from itertools import groupby


rows.sort(key=itemgetter('date'))

for date, items in groupby(rows, key=itemgetter('date')):
    print(date)
    for i in items:
        print(' ', i)

What is important here is to first sort the data according to fields of interest. Because groupby can only check the contiguous items, without first ordering, it will not be the way you want to record the packet.

Method Two:

from collections import defaultdict


rows_by_date = defaultdict(list)
for row in rows:
    rows_by_date[row['date']].append(row)

 

Guess you like

Origin www.cnblogs.com/BeautifulWorld/p/11706126.html