Reputation: 3
As an example if the dictionary was this:
myDict = {"egg sandwich":["bread", "lettuce", "mayo","egg"],
"sad sandwich":["bread","lettuce","mayo"],
"ham sandwich":["bread","lettuce","mayo","ham"],
"healthy sandwich":["lettuce"],
"breakfast sandwich":["bread","egg","mayo"]}
The function should return "ham sandwich" , since it is the only sandwich that contains an ingredient (ham) unique to a comparison of all other lists.
Upvotes: 0
Views: 49
Reputation: 2331
This seems to work:
def get_unique_item(d):
all_ingredients = [y for x in d.values() for y in x]
output = []
for name, ingredients in d.items():
for ingredient in ingredients:
if all_ingredients.count(ingredient) == 1:
output.append(name)
break
return output
myDict = {"egg sandwich":["bread", "lettuce", "mayo","egg"],
"sad sandwich":["bread","lettuce","mayo"],
"ham sandwich":["bread","lettuce","mayo","ham"],
"healthy sandwich":["lettuce"],
"breakfast sandwich":["bread","egg","mayo"]}
print(get_unique_item(myDict))
Output:
['ham sandwich']
Basically, we create a list of all occurrences of all ingredients, and for each sandwich, we check if there are any ingredients which only occur once.
If you really want to, you can make it a one-line list comprehension:
[name for name, ingredients in d.items() if any([y for x in d.values() for y in set(x)].count(i) == 1 for i in ingredients)]
Upvotes: 1