简体   繁体   中英

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.
  2. Iterate through the flower/color data, and add them to the result dictionary.

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:

{'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 .

This can be achieved using two for loops. 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':

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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