将字典数据分组排序

Posted regit

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将字典数据分组排序相关的知识,希望对你有一定的参考价值。

 

一. 使用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},
]

from operator import itemgetter
from itertools import groupby
# Sort by the desired field first
rows.sort(key=itemgetter(date))
# Iterate in groups
for date, items in groupby(rows, key=itemgetter(date)):
    print(date)
    for i in items:
        print( , i)

 

输出结果如下

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

 

以上是关于将字典数据分组排序的主要内容,如果未能解决你的问题,请参考以下文章

spark 例子wordcount topk

学不会的python之通过某几个关键字排序分组一个字典列表(列表中嵌套字典)

学不会的python之通过某几个关键字排序分组一个字典列表(列表中嵌套字典)

根据 pandas 中的字典对数据帧的行进行分组并对相应的分子求和

字典列表,按列表键分组,没有交集

iOS小技能:对象数组按照日期分组和排序,使用块代码实现数组排序和乱序。