0

So, I have a dictionnary

a = {
'a' : 'banana',
'b' : 'orange',
'c' : 'pineapple',
'd' : 'apple' }

I want the keys of banana and orange, so I did :

def dict_values(x) :
    print((list(a.keys())[list(a.values()).index(x)]),end=' ')

and

res = ['banana', 'orange']
for r in res :
    dict_values(r)

the result is a b, but I would like a list for the result like list = ['a', 'b']

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
Nielwig
  • 81
  • 1
  • 6
  • If you find yourself needing to get keys from a dict based on values, it's a very good sign you need to change your design – DeepSpace Mar 10 '19 at 18:11
  • Possible duplicate of [Two way/reverse map](https://stackoverflow.com/questions/1456373/two-way-reverse-map) – albert Mar 10 '19 at 18:13

1 Answers1

1

Here is one way:

>>> a = {
... 'a' : 'banana',
... 'b' : 'orange',
... 'c' : 'pineapple',
... 'd' : 'apple' }
>>> [k for k,v in a.items() if v in set(('banana','orange'))]
['a', 'b']
>>>

The set is only important for large amounts of keys. Note, as @DeepSpace commented, this requirement is indicative of wrong design in your code, and you should consider some other way to structure your data.

kabanus
  • 24,623
  • 6
  • 41
  • 74