i am using a dict like below and i want a function preferably which returns the key value, based on the value user provides.
test_dict={'Name':[abc,def],'Address':['Local','NonLocal']}
Used the below function:
def find_key_for(input_dict,value): result=[] for k,v in input_dict.items(): if value in v: result.append(k) return result
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:
def find_key_for(input_dict, value): result = [] for k, v in input_dict.items(): if value in v: result.append(k) return result
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:
test_dict = {'Name': ['abc', 'def'], 'Address': ['Local', 'NonLocal']} def find_key_for(input_dict, value): return [k for k in input_dict if value in input_dict[k]] print(find_key_for(test_dict, 'abc'))
Or a lambda
function:
test_dict = {'Name': ['abc', 'def'], 'Address': ['Local', 'NonLocal']} find_key_for = lambda input_dict, value: [k for k in input_dict if value in input_dict[k]] print(find_key_for(test_dict, 'abc'))
Output:
['Name']