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
x
2
1
test_dict={'Name':[abc,def],'Address':['Local','NonLocal']}
2
Used the below function:
JavaScript
1
7
1
def find_key_for(input_dict,value):
2
result=[]
3
for k,v in input_dict.items():
4
if value in v:
5
result.append(k)
6
return result
7
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
1
7
1
def find_key_for(input_dict, value):
2
result = []
3
for k, v in input_dict.items():
4
if value in v:
5
result.append(k)
6
return result
7
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
1
7
1
test_dict = {'Name': ['abc', 'def'], 'Address': ['Local', 'NonLocal']}
2
3
def find_key_for(input_dict, value):
4
return [k for k in input_dict if value in input_dict[k]]
5
6
print(find_key_for(test_dict, 'abc'))
7
Or a lambda
function:
JavaScript
1
6
1
test_dict = {'Name': ['abc', 'def'], 'Address': ['Local', 'NonLocal']}
2
3
find_key_for = lambda input_dict, value: [k for k in input_dict if value in input_dict[k]]
4
5
print(find_key_for(test_dict, 'abc'))
6
Output:
JavaScript
1
2
1
['Name']
2