Pedro Tak
Pedro Tak

Reputation: 1

Lambda on Dictionary Condition

Let's say I have a list with a dictionary with and id, score and key. I would like to create a method do return the score given the key using lambda functions.

This method suffices the problem:

def my_search(txt):
    for i in my_dictionary:
        if i['key'] == txt:
            return i['score']

But I'd like to use lambda functions to do that. I've tried to use lambda with a filter, but it doesn't seem to work. How can I proceed?

I have something like

[{'id': 1, 'score': 8.321, 'key': 'stv'}, {'id': 1, 'score': 6.321, 'key': 'mrk'} ... ]

Upvotes: 0

Views: 1403

Answers (4)

Madushanka kahawa
Madushanka kahawa

Reputation: 345

def my_search(txt):
    val = list(filter(lambda elem: elem[0] == txt ,my_dictionary.items()))
    return(val[0][1])

Upvotes: 4

blhsing
blhsing

Reputation: 106618

You can convert my_search to a lambda function using a generator expression like this:

my_search = lambda txt: next(i['score'] for i in my_dictionary if i['key'] == txt)

so that given:

my_dictionary = [
    {'id': 1, 'score': 8.321, 'key': 'stv'},
    {'id': 1, 'score': 6.321, 'key': 'mrk'}
]

my_search('mrk') would return:

6.321

Upvotes: 0

Barmar
Barmar

Reputation: 781096

The function should take a function as an argument, and call the function instead of performing the comparison.

def my_search(func):
    for i in my_dictionary:
        if func(i['key']):
            return i['score']

print(my_search(lambda k: k == txt))

Upvotes: 0

Chris
Chris

Reputation: 16147

txt = 'a'
d = {'a':'b'}
>>> [v for k,v in d.items() if k==txt]
['b']

Upvotes: -1

Related Questions