Python Dict找出value大于某值或key大于某值的所有项方式

对于一个Dict:

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}

如果想要求k或者v某一个就取一个即可:

# -*- 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 Dict找出value大于某值或key大于某值的所有项方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持来客网。