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:
my_lst
into a suitable result
dictionary.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
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments