The naive approaches (looping through all items and looking for the fruit) work but have a high complexity, mostly if you have to perform a lot of requests. You could slightly improve it by replacing your list
values by a set
(for faster in
lookup), but that would still be slow (O(n**2)
=> O(n)
but room for improvement).
If you want to be able to perform those queries a lot of times, it would be better to rebuild the dictionary so lookup is very fast once built, using collections.defaultdict
d = {
"Fruit_1" : ["mango", "apple"],
"Fruit_2" : ["apple"],
"Fruit_3" : ["mango", "banana", "apple", "kiwi", "orange"]
}
import collections
newd = collections.defaultdict(list)
for k,vl in d.items():
for v in vl:
newd[v].append(k)
print(newd)
print(newd["mango"])
this is the rebuilt dict:
defaultdict(<class 'list'>, {'apple': ['Fruit_2', 'Fruit_3', 'Fruit_1'], 'orange': ['Fruit_3'], 'banana': ['Fruit_3'], 'kiwi': ['Fruit_3'], 'mango': ['Fruit_3', 'Fruit_1']})
this is the query for "mango":
['Fruit_3', 'Fruit_1']