0

I have this dictionary_pair and a list_value. I want to be able to use lambda, filter to get a list as [1,2]. I have tried the code below but getting a list as ['ab'].

dictionary_pair = {'ab': [1, 2], 'cd': [3, 1]}

list_value = ['ab', 'yz']

try:  
    result = list(filter(lambda x: dictionary_pair[x], list_value))
except KeyError:  
    pass

2 Answers 2

1

This is just to show you how to use lambda, map, filter. However a simple list-comprehension is preferred in this case

list(filter(None, map(lambda x:dictionary_pair.get(x, None) ,list_value)))
#[[1, 2]]
Sign up to request clarification or add additional context in comments.

Comments

1

I'm assuming you want something like this:

result = [v for k, v in dictionary_pair.items() if k in list_value]

No need to use a lambda, a simple list comprehension works here.

1 Comment

Just to say there is a typo: "if k in list_value]". It is of course an "if" and not "id

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.