我有一个包含以下键和值的字典:
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 : []
答案 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