Mottysc
Mottysc

Reputation: 31

How do I check if an item is in a list which is in a dictionary?

How would I search a list within a dictionary and then retrieve the key? The lists are values of a dictionary and I'm trying to find a specific item within those lists and then return the key.

For example:

wanted_fruit = "granny_smith"
fruits = {
     "oranges" : ["tangerine", "mandarin", "clementine", "blood_orange"],
     "apples" : ["golden_delicious", "gala", "granny_smith", "rome"],
     "melons" : ["watermelon", "honeydew", "cantaloupe"]
}

How would I get an output of apples (as "granny_smith" is within the apples list)?

Upvotes: 1

Views: 67

Answers (4)

Blckknght
Blckknght

Reputation: 104712

There's no efficient way to do a search with the data structure you show. You'd need to scan through all the lists in the dictionary. Now, for a small data set that is still reasonably fast, but it would slow down a lot if you have huge amounts of data. If you're going to do a lot of these searches, you might want to reverse the data structure so that you can look up the keys you care about directly.

data = {
    "oranges" : ["tangerine", "mandarin", "clementine", "blood_orange"],
    "apples" : ["golden_delicious", "gala", "granny_smith", "rome"],
    "melons" : ["watermelon", "honeydew", "cantaloupe"]
}
reversed_data = {variety: fruit_type for fruit_type, varieties in data.items()
                                     for variety in varieties}

Now reversed_data["granny_smith"] will be "apples", and it's a very efficient dictionary lookup. You can do those kinds of checks a lot without needing to inefficiently search through the original data structure again and again.

Upvotes: 2

Rashed Rahat
Rashed Rahat

Reputation: 2475

Try:

result = [k for k, v in fruits.items() if wanted_fruit in v]

print(result)
# Expected Output: ['apples']

Happy coding :)

Upvotes: 0

Ritik Mishra
Ritik Mishra

Reputation: 718

wanted_fruit_category = next(
    (category_name for category_name, category_items in fruits.items() 
                   if wanted_fruit in category_items),
    None
)

A generator expression is used to iterate through all of the items in the dictionary. It evaluates to None if none of the dictionary values contained your wanted_fruit

Upvotes: 0

beesleep
beesleep

Reputation: 1362

Just loop over the dictionnary:

for fruit_type, fruit_lst in fruits.items():
  if wanted_fruit in fruit_lst:
     print(fruit_type)

Upvotes: 0

Related Questions