# 2、解决方案????

itertools.groupby()函数在对数据进行分组时特别有用。

from operator import itemgetter
from itertools import groupby

rows=[
{'name':'mark','age':18,'uid':'110'},
{'name':'miaomiao','age':28,'uid':'160'},
{'name':'miaomiao2','age':28,'uid':'150'},
{'name':'xiaohei','age':38,'uid':'130'},
]

#首先根据age排序
rows.sort(key=itemgetter('age'))

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

18
{'name': 'mark', 'age': 18, 'uid': '110'}
28
{'name': 'miaomiao', 'age': 28, 'uid': '160'}
{'name': 'miaomiao2', 'age': 28, 'uid': '150'}
38
{'name': 'xiaohei', 'age': 38, 'uid': '130'}

# 3、分析

Python实用技法第5篇：一键多值字典：defaultdict

from collections import defaultdict

rows=[
{'name':'mark','age':18,'uid':'110'},
{'name':'miaomiao','age':28,'uid':'160'},
{'name':'miaomiao2','age':28,'uid':'150'},
{'name':'xiaohei','age':38,'uid':'130'},
]

rows_by_age=defaultdict(list)
for row in rows:
rows_by_age[row['age']].append(row)
for a in rows_by_age[28]:
print(a)

{'name': 'miaomiao', 'age': 28, 'uid': '160'}
{'name': 'miaomiao2', 'age': 28, 'uid': '150'}