6

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?

Nikaido
  • 4,443
  • 5
  • 30
  • 47
Jonas
  • 67
  • 1
  • 1
  • 6
  • Is `red` supposed to be `"red"`, and similarly for `blue` and `green`? And what have you tried? – Rory Daulton Nov 08 '16 at 20:24
  • 2
    Side note: Don't use `dict` for your dictionary name, as it is a `builtin`. Use something more descriptive like `colors` or `color_dict` – Billy Nov 08 '16 at 20:27
  • @RoryDaulton I haven't really tried anything worth posting here. – Jonas Nov 08 '16 at 20:38
  • You basically used the dictionary the wrong way. They are made to lookup a value by a key, not the othervway around. If you just have to do it once, the rather expensive solutions beliw might be ok, but if you have to run many of these lookups in a large dictionary, you might want to have a second dictionary the has the values you are looking for as keys and the list of keys from the first dictionary that contain these colors as values. – Klaus D. Nov 08 '16 at 21:50

2 Answers2

8

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

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
1

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)
Nikaido
  • 4,443
  • 5
  • 30
  • 47