[英]Return keys of dictionary if values match with a given list
如果字典中的值與列表的元素匹配,我想返回給定字典的所有鍵。 假設我有以下字典:
my_dict = {'flower1': ['blue'],
'flower2': ['red', 'green', 'blue'],
'flower3': ['yellow'],
'flower4': ['blue', 'black', 'cyan']}
現在我想將字典中的值與列表中的以下元素進行匹配:
my_lst = ['black',
'red',
'blue',
'yellow',
'green',
'purple',
'brown',
'cyan']
我的目標是獲得如下字典:
result_dict = {'black': ['flower4'],
'red': ['flower2'],
'blue': ['flower1', 'flower2', 'flower4'],
'yellow': ['flower3']
'green': ['flower2'],
'purple': [],
'brown': [],
'cyan': []}
現在我嘗試了一個簡單的列表理解,它工作正常,但只返回一個簡單的無序列表,如:
In[14]: [key for key, value in my_dict.items() for i in range(0, len(my_lst)) if my_lst[i] in value]
Out[14]:['flower1',
'flower2',
'flower2',
'flower2',
'flower3',
'flower4',
'flower4',
'flower4']
執行此類操作的最佳方法是什么? 我無法理解它,任何幫助將不勝感激。
不要過度復雜化。 分兩個完全獨立的步驟進行:
my_lst
轉換為合適的result
字典。result
字典中。例如:
# create result dict, adding each color as a key
# make the value of each key an empty list initially
result = {k: [] for k in my_lst}
# iterate through the items of the flower/color dict
for flower, colors in my_dict.items():
# append the flower corresponding to each color
# to the appropriate list in the result dict
for color in colors:
result[color].append(flower)
print(result)
Output:
{'black': ['flower4'], 'red': ['flower2'], 'blue': ['flower1', 'flower2', 'flower4'], 'yellow': ['flower3'], 'green': ['flower2'], 'purple': [], 'brown': [], 'cyan': ['flower4']}
當然,這假設my_lst
my_dict
。
這可以使用兩個 for 循環來實現。 它比使用單線更具可讀性。 我提供了一個代碼片段,它完全符合您的要求,並且非常直觀地理解它是如何工作的。 如果可以在值列表中找到該元素,則獲取每個列表元素並檢查每個鍵。
result_dict = {}
for ele in my_lst:
result_dict[ele] = []
for key in my_dict.keys():
if ele in my_dict[key]:
result_dict[ele].append(key)
這個 function 可以用來替代你的“result_dict”:
def flowers_by_color(color, data = my_dict):
return [flower for flower in data.keys() if color in data[flower]]
result_dict = {color:flowers_by_color(color) for color in my_lst}
你可以這樣做:
result_dict = {color: [] for color in my_lst}
for flower in my_dict:
for color in my_dict[flower]:
if color in my_lst:
result_dict[color].append(flower)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.