python - 过滤字典中的项目

标签 python

<分区>

有没有办法返回内部字典的值符合特定条件的键列表

给定一个 python 字典:

adict = {
    1: {'process':False, 'length':10},
    2: {'process':True, 'length':34},
    ...,
    n: {'process': False, 'length: -3'}
}

有没有一种方法可以获得键列表 [1, 2, 6...] 谁的内部字典符合我想要的标准?

def somefiltering(critieria1, critieria2, critieria3...):
    # for variable number of critieria
    # logic
    return list of keys

我知道我可以简单地“循环”我的字典,但有没有更好的方法?还有

如何格式化 somefiltering 和格式化 criteria1 以使其工作?
只输入 criteria1 = "process = True",行不通?

最佳答案

这里有一个方法:

adict = {1: {'process':False, 'length':10}, 2: {'process':True, 'length':34}, 3:{'process': False, 'length': -3}}

def somefiltering(filterDict, *criteria):
    return [key for key in filterDict if all(criterion(filterDict[key]) for criterion in criteria)]

请注意,您的 somefiltering 函数需要将字典作为参数。

示例用法:

somefiltering(adict, lambda d:d['process'], lambda d:d['length']>5)
# Result: [2]

somefiltering(adict, lambda d:d['length'] < 20)
# Result: [1, 3]

somefiltering(adict, lambda d:d['process'], lambda d:d['length']<5)
# Result: []

关于python - 过滤字典中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19393576/

相关文章:

python - Flask-WTF SelectMultipleField 使用数据库 ID 而不是名称填充

Python 3.3 for() 循环迭代处理时间呈指数增长?

python - tcpkill : write: Operation not permitted with subprocess. 弹出

python - 我可以让 Beautiful Soup 保持属性排序和行缩进吗

javascript - Ajax 返回整页

python - scikit-learn 中的 apply() 函数可以做什么?

python - 当将索引定位为 x 轴时,从 df.pivot 绘图返回 AttributeError

python - 根据另一个变量的值为变量赋值的优雅方式

python - 如何通过pyspark读取gz压缩文件

python - SQLAlchemy MySQL STRAIGHT_JOIN