Python 3:如果包含特定字符串,则如何搜索和检索构成字典的所有列表

时间:2017-06-30 10:53:34

标签: python list python-3.x dictionary search

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

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 : []

3 个答案:

答案 0 :(得分:2)

dictionary = { k : [ x for x in v if "hot" in x ] for k, v in dictionary.items() }

答案 1 :(得分:0)

{key: [value for value in values if 'hot' in value] for (key, values) in my_dict.items()}

答案 2 :(得分:0)

试试这个:

#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