Python字典筛选:提取Key或Value大于指定值的项
本文介绍在Python中如何高效筛选字典中Key或Value大于特定值的项。通过字典推导式{ k:v for k, v in test_dict.items() if ...}可快速过滤。同时补充使用filter和lambda表达式处理列表筛选的方法,帮助开发者掌握数据过滤的核心技巧。
Python字典筛选Key或Value大于指定值的方法
假设有一个字典对象:
test_dict = {1:5, 2:4, 3:3, 4:2, 5:1}
若需提取Key值大于等于3的所有键值对:
print({k:v for k, v in test_dict.items() if k>=3})
运行结果为:
{3: 3, 4: 2, 5: 1}
若需提取Value值大于等于3的所有键值对:
print({k:v for k, v in test_dict.items() if v>=3}) {1: 5, 2: 4, 3: 3}
若只需获取Key或Value中满足条件的单一列表,可调整推导式结构:
# -*- coding:utf-8 -*-
__author__ = 'ShawDa'
test_dict = {1:5, 2:4, 3:3, 4:2, 5:1}
print({k:v for k, v in test_dict.items() if k>=3})
print({k:v for k, v in test_dict.items() if v>=3})
print([k for k, v in test_dict.items() if k>=3])
print([k for k, v in test_dict.items() if v>=3])
print([v for k, v in test_dict.items() if k>=3])
print([v for k, v in test_dict.items() if v>=3])
补充知识:利用列表解析式筛选出大于5的数字[1,2,3,4,5,6,7,8,9]
list(filter(lambda x:x>5,[1,2,3,4,5,6,7,8,9])) #filter函数 python 中一个高阶函数,过滤器 filter 函数接受一个函数func和一个列表,这个函数func的作用是对每个元素进行判断,返回True和False来过滤掉不符合条件的元素
以上关于Python字典筛选Key或Value大于某值的方法分享完毕,希望能为读者提供实用参考。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













