Selecting elements of a Python dictionary greater than a certain value

前端 未结 3 1468
自闭症患者
自闭症患者 2020-12-24 11:53

I need to select elements of a dictionary of a certain value or greater. I am aware of how to do this with lists, Return list of items in list greater than some value

3条回答
  •  粉色の甜心
    2020-12-24 12:50

    .items() will return (key, value) pairs that you can use to reconstruct a filtered dict using a list comprehension that is feed into the dict() constructor, that will accept an iterable of (key, value) tuples aka. our list comprehension:

    >>> d = dict(a=1, b=10, c=30, d=2)
    >>> d
    {'a': 1, 'c': 30, 'b': 10, 'd': 2}
    >>> d = dict((k, v) for k, v in d.items() if v >= 10)
    >>> d
    {'c': 30, 'b': 10}
    

    If you don't care about running your code on python older than version 2.7, see @opatut answer using "dict comprehensions":

    {k:v for (k,v) in dict.items() if v > something}
    

提交回复
热议问题