Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return key if a given string matches the keys value in a dictionary [duplicate]

I am new to dictionaries, and i'm trying to find out how to return a key if a given string matches the keys value in a dictionary.

Example:

dict = {"color": (red, blue, green), "someothercolor": (orange, blue, white)}

I want to return color and someothercolor, if the key's value contains blue.

Any suggestions?

like image 206
Jonas Avatar asked Nov 08 '16 20:11

Jonas


2 Answers

You may write list comprehension expression as:

>>> my_dict = {"color": ("red", "blue", "green"), "someothercolor": ("orange", "blue", "white")}

>>> my_color = "blue"
>>> [k for k, v in my_dict.items() if my_color in v]
['color', 'someothercolor']

Note: Do not use dict as variable because dict is built-in data type in Python

like image 65
Moinuddin Quadri Avatar answered Sep 19 '22 12:09

Moinuddin Quadri


the solution is (without comprehension expression)

my_dict = {"color": ("red", "blue", "green"), "someothercolor": ("orange", "blue", "white")}
solutions = []
my_color = 'blue'
for key, value in my_dict.items():
    if my_color in value:
        solutions.append(key)
like image 39
Nikaido Avatar answered Sep 18 '22 12:09

Nikaido