Python using filter() with a dict

Viewed 1092

So I have this dict

dic = { 0: [3,6,4], 1: [1,1,2], 2: [3,5,3], 3: [1,7,4], 4: [1,3,3], 5: [4,4,6] } 

and I'd like to create another dictionary where the sum() of each list is > 10 using filter() and lambda expressions.

Outpout desired: { 0: [3,6,4], 2: [3,5,3], 3: [1,7,4], 5: [4,4,6] }

I tried something like

dict(filter(lambda e: sum(e[1]) > 10, dic.items()))

but it doesn't work at all

Edit:

Ok, I just solved.

dict(filter(lambda e: sum(e[1][::]) > 10, dic.items()))
3 Answers

I think its much nicer to use a dictionary comprehension instead of dict(filter(...)):

>>> dic = { 0: [3,6,4], 1: [1,1,2], 2: [3,5,3], 3: [1,7,4], 4: [1,3,3], 5: [4,4,6] }
>>> {k: v for k, v in dic.items() if sum(v) > 10}
{0: [3, 6, 4], 2: [3, 5, 3], 3: [1, 7, 4], 5: [4, 4, 6]}

You were on the right track! Only problem is you declared a variable with the name dict which is reserved in python:

# changed name to data
data = { 0: [3,6,4], 1: [1,1,2], 2: [3,5,3], 3: [1,7,4], 4: [1,3,3], 5: [4,4,6] }

dict(filter(lambda e: sum(e[1]) > 10, data.items()))

Output:

{0: [3, 6, 4], 2: [3, 5, 3], 3: [1, 7, 4], 5: [4, 4, 6]}

Looks good to me!

I try to avoid using function/object names as variables by using underscores. So instead of dict = {...} you could do person_dict = {...}.

You could use filter and lambda in the following way to achieve the correct output.

dic = { 0: [3,6,4], 1: [1,1,2], 2: [3,5,3], 3: [1,7,4], 4: [1,3,3], 5: [4,4,6] }
threshold = 10
filtered_dic = dict(filter(lambda l: sum(l[1]) > threshold, dic.items()))
print(filtered_dic)
Related