[英]How can I create a dictionary from two lists, one list is the keys, the other contains nested values?
[英]Given a dictionary with lists of strings as their values, how would you retrieve all keys where the list contains a string unique to all other lists?
例如,如果字典是這樣的:
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"]}
該函數應返回“火腿三明治”,因為它是唯一包含與所有其他列表進行比較時所獨有的成分(火腿)的三明治。
這似乎有效:
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))
輸出:
['ham sandwich']
基本上,我們創建一個所有成分的所有出現的列表,對於每個三明治,我們檢查是否有任何成分只出現一次。
如果你真的想,你可以把它變成一個單行列表理解:
[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)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.