Python程式設計:itemgetter獲取字典元素和groupby分組
阿新 • • 發佈:2018-11-24
itemgetter獲取字典元素
groupby分組
程式碼示例
from itertools import groupby
from operator import itemgetter
d1 = {"name": "Tom", "age": 23, "country": "cn"}
d2 = {"name": "Jimi", "age": 21, "country": "en"}
d3 = {"name": "Tomy", "age": 22, "country": "usa"}
d4 = {"name": "Mimi", "age": 23, "country": "cn" }
d5 = {"name": "Jack", "age": 24, "country": "en"}
lst = [d1, d2, d3, d4, d5]
# 排序
lst.sort(key=itemgetter("country"))
# lst.sort(key=lambda x: x["country"])
for d in lst:
print(d)
"""
{'name': 'Tom', 'age': 23, 'country': 'cn'}
{'name': 'Mimi', 'age': 23, 'country': 'cn'}
{'name': 'Jimi', 'age': 21, 'country': 'en'}
{'name': 'Jack', 'age': 24, 'country': 'en'}
{'name': 'Tomy', 'age': 22, 'country': 'usa'}
"""
# 分組
groups = groupby(lst, key=itemgetter("country"))
# groups = groupby(lst, key=lambda x: x["country"])
for key, group in groups:
print(key)
for g in group:
print("\t", g)
"""
cn
{'name': 'Tom', 'age': 23, 'country': 'cn'}
{'name': 'Mimi', 'age': 23, 'country': 'cn'}
en
{'name': 'Jimi', 'age': 21, 'country': 'en'}
{'name': 'Jack', 'age': 24, 'country': 'en'}
usa
{'name': 'Tomy', 'age': 22, 'country': 'usa'}
"""