python3:如果包含特定字符串,如何搜索和检索组成字典的所有列表

2024-05-16 08:22:57 发布

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

我有一本包含以下键和值的字典:

Pasta : [['Tomato', 'hot'], ['Vegetables', 'Lemon', 'cold'],
        ['Cheese','hot']]
Cookies : [['Chocolate', 'Nuts', 'hot'], ['Chocolate', 'Pistachio', 'hot']]
Salad : [['Mushrooms', 'Lettuce', 'cold'], ['Lettuce', 'Fruits', 'cold']]

假设对于每个键,我希望保留包含字符串“hot”的所有值,以获得:

Pasta : [['Tomato', 'hot'], ['Cheese','hot']]
Cookies : [['Chocolate', 'Nuts', 'hot'], ['Chocolate', 'Pistachio', 'hot']]
Salad : []

Tags: 字典lemoncookiesnutshotlettucecheesepasta
3条回答
{key: [value for value in values if 'hot' in value] for (key, values) in my_dict.items()}

试试这个:

#create function to get hot or cold menu items
def get_menu(dictionary,temp):
    temp_dict = {}
    for k,v in dictionary.items():
        temp_dict[k] = []
        for sl in v:
            if temp in sl:
                temp_dict[k].append(sl)
    return temp_dict

menu = {'Pasta' : [['Tomato', 'hot'],['Vegetables', 'Lemon', 'cold'],['Cheese','hot']],
     'Cookies' : [['Chocolate', 'Nuts', 'hot'], ['Chocolate', 'Pistachio', 'hot']],
     'Salad' : [['Mushrooms', 'Lettuce', 'cold'], ['Lettuce', 'Fruits', 'cold']]}
#get hot menu items
hot_menu = get_menu(menu,"hot")
#get cold menu items
cold_menu = get_menu(menu,"cold")

#print results
print ("\n\n**** Hot Menu ****")
for key,value in hot_menu.items():
    if not value:
        continue
    print ("-"*25)
    print (key+": ")
    for sublist in value:
        sublist.remove("hot")
        print (" | "+" ".join(sublist))

print ("\n\n**** Cold Menu ****")
for key,value in cold_menu.items():
    if not value:
        continue
    print ("-"*25)
    print (key+": ")
    for sublist in value:
        sublist.remove("cold")
        print (" | "+" ".join(sublist))

输出:

**** Hot Menu ****
            -
Cookies: 
 | Chocolate Nuts
 | Chocolate Pistachio
            -
Pasta: 
 | Tomato
 | Cheese


**** Cold Menu ****
            -
Pasta: 
 | Vegetables Lemon
            -
Salad: 
 | Mushrooms Lettuce
 | Lettuce Fruits
dictionary = { k : [ x for x in v if "hot" in x ] for k, v in dictionary.items() }

相关问题 更多 >