码迷,mamicode.com
首页 > 编程语言 > 详细

将字典数据分组排序

时间:2018-07-31 19:27:56      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:rom   rto   import   imp   tor   nbsp   字段   group   字典   

 

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

 

将字典数据分组排序

标签:rom   rto   import   imp   tor   nbsp   字段   group   字典   

原文地址:https://www.cnblogs.com/regit/p/9397197.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!