Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if dictionary lists contain value and return keys

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

like image 283
haagn Avatar asked Sep 08 '25 14:09

haagn


1 Answers

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]
like image 169
Ajax1234 Avatar answered Sep 10 '25 03:09

Ajax1234