Python >> Programma Python >  >> Python

Come raggruppare i dati per chiave in un dizionario in Python

Problema –

Hai un elenco di dizionari e desideri raggruppare i dati in base a una chiave nel dizionario.

customers = [{'customer':1, 'net sales': 39.5, 'method':'Discover'},
            {'customer':2, 'net sales': 102.4, 'method':'Proprietary'},
            {'customer':3, 'net sales': 22.5, 'method': 'Proprietary'},
            {'customer':4, 'net sales': 100.4, 'method': 'Proprietary'},
            {'customer':5, 'net sales': 54.0, 'method': 'MasterCard'},
            {'customer':6, 'net sales': 75.0, 'method': 'Discover'}]

Soluzione –

Supponiamo che tu voglia raggruppare i dati in base al metodo di pagamento. Questo può essere fatto utilizzando itertools.groupby funzione. Per prima cosa dobbiamo ordinare i dati in base alla chiave desiderata in questo caso "metodo" e quindi utilizzare itertools.groupby .

In [10]: from operator import itemgetter

In [11]: from itertools import groupby

In [12]: # sort the data by desired key first

In [13]: customers.sort(key=itemgetter('method'))

In [14]: # then iterate in groups

In [15]: for method, items in groupby(customers, key=itemgetter('method')):
    ...:     print(method)
    ...:     for i in items:
    ...:         print('    ', i)
    ...:         
Discover
     {'customer': 1, 'net sales': 39.5, 'method': 'Discover'}
     {'customer': 6, 'net sales': 75.0, 'method': 'Discover'}
MasterCard
     {'customer': 5, 'net sales': 54.0, 'method': 'MasterCard'}
Proprietary
     {'customer': 2, 'net sales': 102.4, 'method': 'Proprietary'}
     {'customer': 3, 'net sales': 22.5, 'method': 'Proprietary'}
     {'customer': 4, 'net sales': 100.4, 'method': 'Proprietary'}