I have a dictionary with a set of key:value pairs where the values are a lists like so:
my_dict = {7: [6, 13], 6: [7, 8, 9, 11, 13, 14], 8: [6, 14], 9: [6], 11: [6], 13: [6, 7], 14: [6, 8]}
I want to check which of the lists contain the value '6' and return the keys which correspond to the matches. (i.e. 7, 8, 9, 11, 13 and 14)
I have tried the following code:
def find_key_for(input_dict, value):
for k, v in input_dict.items():
if v == value:
yield k
else:
return "None"
keys = list(find_key_for(my_dict, 6))
But it returns the following error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
How can I work around this issue to return all the keys whos lists contain this value? Thanks
You can use dict.items()
:
my_dict = {7: [6, 13], 6: [7, 8, 9, 11, 13, 14], 8: [6, 14], 9: [6], 11: [6], 13: [6, 7], 14: [6, 8]}
new_dict = [a for a, b in my_dict.items() if 6 in b]
Output:
[7, 8, 9, 11, 13, 14]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With