Python编程:itemgetter获取字典元素和groupby分组

版权声明:本文为博主原创文章,欢迎转载,请注明出处 https://blog.csdn.net/mouday/article/details/84205629

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'}
"""

参考
Python中的分组函数(groupby、itertools)

阅读更多

扫码向博主提问

彭世瑜

非学,无以致疑;非问,无以广识
  • 擅长领域:
  • python
  • python爬虫
  • python全栈
去开通我的Chat快问

没有更多推荐了,返回首页