filter()python中的dict-仅返回键

filter()python中的dict-仅返回键,python,dictionary,Python,Dictionary,我想过滤一个字典,当它们有一个特定的值时,我会在字典中得到键,我只想从字典中返回键。下面是我的代码: def smaller_than(d, value): result = filter(lambda x: x[1]<=3, d.items()) return result number_key = {35135135: 5, 60103513: 3, 10981179: 2, 18637724 : 4} number = smaller_than(number_key

我想过滤一个字典,当它们有一个特定的值时,我会在字典中得到键,我只想从字典中返回键。下面是我的代码:

def smaller_than(d, value):
    result = filter(lambda x: x[1]<=3, d.items())
    return result

number_key = {35135135: 5, 60103513: 3, 10981179: 2, 18637724 : 4}
number = smaller_than(number_key, 3)
print(number)
def小于(d,值):

结果=过滤器(λx:x[1]第一个解决方案,只需添加:

new_list = []
for i in number:
    new_list.append(i[0])

print new_list
第二种解决方案:

def smaller_than(d, value):
    result = filter(lambda x: x[1]<=3, d.items())
    result = map(lambda x: x[0], result)
    return result

number_key = {35135135: 5, 60103513: 3, 10981179: 2, 18637724 : 4}
number = smaller_than(number_key, 3)
print(number)
def小于(d,值):

result=filter(lambda x:x[1]您不必将
d.items()
作为可用于
filter
的参数进行传递。只需传递
dict
对象(与
dict.keys()
相同),并使用lambda表达式基于
dict[key]
对内容进行过滤,如下所示:

>>number_key={35135135:560103513:310981179:218637724:4}

>>>筛选(lambda x:number_key[x]或者,您也可以使用列表理解表达式筛选字典,如下所示:

>>> number_key = {35135135: 5, 60103513: 3, 10981179: 2, 18637724 : 4}

>>> [k for k, v in number_key.items() if v<= 3]
[60103513, 10981179]
>>number_key={35135135:560103513:310981179:218637724:4}

>>>[k代表k,v在number_key.items()中,如果使用列表理解。它只需要一行
>>> number_key = {35135135: 5, 60103513: 3, 10981179: 2, 18637724 : 4}

>>> [k for k, v in number_key.items() if v<= 3]
[60103513, 10981179]