Skip to content
Advertisement

Python>Finding key based on values within a list, from a dictionary

i am using a dict like below and i want a function preferably which returns the key value, based on the value user provides.

JavaScript

Used the below function:

JavaScript

when i use the above function as below:

print(find_key_for(test-dict,'abc')) it returns [] while i expected Name

alternatively when i do (find_key_for(test-dict,'Local')) it returns [Address] which is expected.

why does it not work for Name? what changes can i make?

Advertisement

Answer

You need to un-indent the return statement:

JavaScript

The reason is because if you don’t, and have it inside the for loop, your function will return after only looping once.

Finally, you can use a nested list comprehension in just one line:

JavaScript

Or a lambda function:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement