如果列表中存在值,则返回键(来自字典)

2024-09-30 20:28:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典:

meals = {'Pasta Bolognese' : ['pasta', 'tomato sauce', 'ground beef'],
    'Cold Salad' : ['greens', 'tomato'],
    'Warm Salad' : ['greens', 'tomato', 'corn', 'chickpeas', 'quinoa'],
    'Sandwich' : ['bread', 'turkey slices', 'cheese', 'sauce']}

和一份清单:

ingredients = ['bread', 'chickpeas', 'tomato', 'greens']

我想从字典中获取一个键,如果它的所有值都在列表中。所以就目前的情况而言,我想要“冷沙拉”,因为“绿色”和“西红柿”都在列表中


Tags: 列表字典saucebeefgroundmealspastatomato
2条回答

您可以使用:

>>> next((k for k, v in meals.items() if set(v).issubset(ingredients)))
'Cold Salad'
>>> 

请注意,这段代码使用带有next的生成器,也可以更有效地使用多个in语句,而不是all和带有in的循环,我使用^{}检查一个集合中的所有值是否都是另一个集合的子集

如果可能没有匹配项,请在末尾添加None

next((k for k, v in meals.items() if set(v).issubset(ingredients)), None)

或者任何东西,您可以用任何东西来替换None,例如"No Match"

您可以使用列表理解,如下所示:

meals = {'Pasta Bolognese' : ['pasta', 'tomato sauce', 'ground beef'],
        'Cold Salad' : ['greens', 'tomato'],
        'Warm Salad' : ['greens', 'tomato', 'corn', 'chickpeas', 'quinoa'],
        'Sandwich' : ['bread', 'turkey slices', 'cheese', 'sauce'], 
        'Another Item': ['greens', 'bread']}

ingredients = ['bread', 'chickpeas', 'tomato', 'greens']

output = [key for key, value in meals.items() if set(value).issubset(ingredients)]

print(output)

结果:

['Cold Salad', 'Another Item']

您会注意到我添加了Another Item来测试将返回多个匹配项

相关问题 更多 >