Reputation: 23
I want to filter a dictionary, where I get the keys when they have a specific value, and just want to return the keys from the dict. Here is my code:
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)
There I get a result like [(60103513, 3), (10981179, 2)], but I just want to get it like [60103513, 10981179]. I think it is a easy answer but I don't know how to do this.
Upvotes: 2
Views: 2213
Reputation: 48120
Alternatively, you may also use a list comprehension expression to filter your dictionary as:
>>> number_key = {35135135: 5, 60103513: 3, 10981179: 2, 18637724 : 4}
>>> [k for k, v in number_key.items() if v<= 3]
[60103513, 10981179]
Upvotes: 1
Reputation: 431
first solution, just add:
new_list = []
for i in number:
new_list.append(i[0])
print new_list
second solution:
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)
Upvotes: 0
Reputation: 48120
You do not have to pass d.items()
as an iterable to filter
. Just pass the dict
object (same as dict.keys()
) and filter the content based on dict[key]
with lambda expression as:
>>> number_key = {35135135: 5, 60103513: 3, 10981179: 2, 18637724 : 4}
>>> filter(lambda x: number_key[x]<=3, number_key)
[60103513, 10981179]
Upvotes: 2