迭代字典

Sun*_*eTS 0 python dictionary loops

我试图返回字典中值大于int argurment的所有值.

def big_keys(dict, int):
    count = []
    for u in dict:
        if u > int:
            count.append(u)
    return count
Run Code Online (Sandbox Code Playgroud)

我不明白为什么这不起作用.它返回列表中的每个值,而不仅仅是那些大于in的值.

Bur*_*lid 7

默认情况下,任何dict都会遍历其键,而不是其值:

>>> d = {'a': 1, 'b': 2}
>>> for i in d:
...    print i
... 
a
b
Run Code Online (Sandbox Code Playgroud)

要迭代值,请使用.values():

>>> for i in d.values():
...    print i
... 
1
2
Run Code Online (Sandbox Code Playgroud)

考虑到这一点,您的方法可以简化:

def big_keys(d, i):
   return [x for x in d.values() if x > i]
Run Code Online (Sandbox Code Playgroud)

我已经改变了你的变量名,因为dictint都是内置插件.

您的方法实际上正在重新创建Python中可用的默认功能.该filter方法执行您要执行的操作:

>>> d = {'a': 1, 'b': 6, 'd': 7, 'e': 0}
>>> filter(lambda x: x > 5, d.values())
[6, 7]
Run Code Online (Sandbox Code Playgroud)

从您的评论看来,您似乎在寻找而不是值.以下是您将如何做到这一点:

>>> d = {'a': 21, 'c': 4, 'b': 5, 'e': 30, 'd': 6, 'g': 4, 'f': 2, 'h': 20}
>>> result = []
>>> for k,v in d.iteritems():
...    if v > 20:
...       result.append(k)
...
>>> result
['a', 'e']
Run Code Online (Sandbox Code Playgroud)

或者,更短的方式:

>>> [k for k,v in d.iteritems() if v > 20]
['a', 'e']
Run Code Online (Sandbox Code Playgroud)