Home > Software engineering >  Find keys in a dictionary of lists using values
Find keys in a dictionary of lists using values

Time:10-06

I have a dictionary that contains multiple values per a key. I would like to use one of the values to get all the keys associated with the value. However my code runs with a null response.

def dict_keys(my_dict, *vals):
for k, v in my_dict.items():
    if v == ['vals']:
        return key
    else:
        return 'No keys' 
return dict_keys

dict_keys(fruit_dict, 'melon', 'strawberries')

'No keys'

However I cannot, grab a single value within a list:

for key, value in fruit_dict.items():  
    print(value)
    print(value == 'melon')
 
output:

['melon', 'berry', 'mango']
False
['orange']
False
['lime']
False
['berry', 'watermelon', 'strawberry']
False
['cherry', 'melon']
False

CodePudding user response:

iterate over the values with a second loop!

for key, fruits in fruit_dict.items():
    for fruit in fruits:
        if fruit == test_fruit:
            ...

or check for membership

for key, fruits in fruit_dict.items():
    if test_fruit in fruits:
        ...

CodePudding user response:

  1. v == [...] isn't how you check if v is one of the members in the list.
  2. vals is already a list. You don't need to wrap it in brackets. And anyway, your ['vals'] is a list that contains a single string -- the string 'vals'
  3. You want all keys that contain the fruit, so you need to finish the loop and return the list of keys after you've processed all keys.
  4. Your function's return type should be consistent. To return something that indicates nothing, it's better to return None. In this case, since we're returning a list, it's better to just return an empty list.
  5. You want to pass a single fruit and get all the keys that contain that fruit.
  6. I suggest you use descriptive names for variables. For example, in for k, v in my_dict.items(), k, v doesn't really tell you what those variables are, but if you rename them to something that makes sense, it's easier to understand what your code is meant to be doing.
def dict_keys(my_dict, search_fruit):
    keys = [] # Initialize an empty list
    for person, liked_fruits in my_dict.items():
        if search_fruit in liked_fruits: # Check if the list contains the fruit you're looking for
            keys.append(person)
        else:
            # Do nothing
            pass
    return keys

Now suppose you have a dictionary like so, which tells you the favorite fruit of five people, and you want to find the people that like melon:

fruit_dict = {
 "A": ['melon', 'berry', 'mango'],
 "B": ['orange'],
 "C": ['lime'],
 "D": ['berry', 'watermelon', 'strawberry'],
 "E": ['cherry', 'melon']
}

You'd do:

dict_keys(fruit_dict, "melon")

which would give you a list containing two keys:

 ['A', 'E']

CodePudding user response:

You can use set.intersection and save yourself a nested loop:

def keys_with_vals(my_dict, *vals):
    check_vals = set(vals).intersection
    return [k for k, v in my_dict.items() if check_vals(v)]
  • Related