简体   繁体   English

如果值与给定列表匹配,则返回字典的键

[英]Return keys of dictionary if values match with a given list

I want to return all the keys of a given dictionary, if the values inside the dictionary match to the elements of a list.如果字典中的值与列表的元素匹配,我想返回给定字典的所有键。 Suppose I have the following dictionary:假设我有以下字典:

my_dict = {'flower1': ['blue'], 
           'flower2': ['red', 'green', 'blue'],
           'flower3': ['yellow'],
           'flower4': ['blue', 'black', 'cyan']}

Now I want to match the values in the dictionary with the following elements in a list:现在我想将字典中的值与列表中的以下元素进行匹配:

my_lst = ['black',
          'red',
          'blue',
          'yellow',
          'green',
          'purple',
          'brown',
          'cyan']

My goal is the get a dictionary like follows:我的目标是获得如下字典:

result_dict = {'black': ['flower4'], 
               'red': ['flower2'],
               'blue': ['flower1', 'flower2', 'flower4'],
               'yellow': ['flower3']
               'green': ['flower2'], 
               'purple': [],
               'brown': [],
               'cyan': []}

For now I have tried a simple list comprehension, which works fine, but returns just a simple and unordered list like:现在我尝试了一个简单的列表理解,它工作正常,但只返回一个简单的无序列表,如:

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']

What is the best way to perform such an operation?执行此类操作的最佳方法是什么? I can't get my head around it, any help would be appreciated.我无法理解它,任何帮助将不胜感激。

Don't over-complicate it.不要过度复杂化。 Do it in two completely separate steps:分两个完全独立的步骤进行:

  1. Convert my_lst into a suitable result dictionary.my_lst转换为合适的result字典。
  2. Iterate through the flower/color data, and add them to the result dictionary.遍历花/颜色数据,并将它们添加到result字典中。

For example:例如:

# 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: Output:

{'black': ['flower4'], 'red': ['flower2'], 'blue': ['flower1', 'flower2', 'flower4'], 'yellow': ['flower3'], 'green': ['flower2'], 'purple': [], 'brown': [], 'cyan': ['flower4']}

This of course, assumes that each color in my_dict occurs in my_lst .当然,这假设my_lst my_dict

This can be achieved using two for loops.这可以使用两个 for 循环来实现。 It is way more readable than using a one-liner.它比使用单线更具可读性。 I have provided a code snippet that does exactly what you want and it is fairly intuitive to understand how it works.我提供了一个代码片段,它完全符合您的要求,并且非常直观地理解它是如何工作的。 You take every list element and check for each key if that element can be found among the list of values.如果可以在值列表中找到该元素,则获取每个列表元素并检查每个键。

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)

This function can be used as replacement of your 'result_dict':这个 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}

You can do something like that:你可以这样做:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM