0

I have searched online but have not found the answer specific to my query.

In Python 3 dictionaries how can I get the key by providing value (the use of a condition). For example, if I had a dictionary with pet names and their quantity:

my_dict = {'cats' : '5', 'dogs' : '4', 'fish' : '7', 'rabbits': '4'}

How would you use a condition to get all keys 'dogs' and 'rabbits' by providing their value (quantity) e.g. 4 in this case?

I read an input file and store a line in a list (by splitting the string), then access this quantity number by using my_list[2] and get this number 4 from there. I then need to check if any pets correspond to this quantity in another dictionary.

To get the pets with this quantity, I have used this approach:

for key, value in my_dict():
            if value == my_list[2]:
                print (key)

but it only gives me one key, not all keys associated with value 4.

EDIT: it turns out this part of the code was working as expected but the actual problem was that, during debugging, in the input file I had changed the value of this variable (and forgot to change it back) which was only matching with one value in my dictionary, hence only returned one key. Many thanks to all who responded and advised.

mrT
  • 86
  • 3
  • 9
  • 2
    This code will error out: `TypeError: 'dict' object is not callable`. Please post a [mcve]. – ForceBru Jan 31 '20 at 16:58
  • 3
    Does this answer your question? [Get key by value in dictionary](https://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary) – deadvoid Jan 31 '20 at 17:01
  • All the comments were very help, much appreciated guys! – mrT Feb 05 '20 at 10:14

3 Answers3

5

You need to go through all of the keys and see which ones have the desired value associated.

my_dict = {'cats' : '5', 'dogs' : '4', 'fish' : '7', 'rabbits': '4'}
four = [k for k in my_dict if my_dict[k] == '4']

Resulting value of four:

['dogs', 'rabbits']

This is also answered nicely here: https://stackoverflow.com/a/44664263/11264793

dacx
  • 824
  • 1
  • 9
  • 18
Prune
  • 76,765
  • 14
  • 60
  • 81
1

Use dict.items() to get the key and value per entry in the dict

for key, value in dict.items():
            if value == '4':
                print (key)
Sushan
  • 61
  • 1
  • 1
    Good answer, but I would have preferred to use a variable (such as my_list[2]) instead of a hardcoded value of 4 :-) – mrT Feb 05 '20 at 10:12
1

You should use dict.items() to iterate over all key, value pairs in a dictionary:

dict = {'cats' : '5', 'dogs' : '4', 'fish' : '7', 'rabbits': '4'}
my_list = ['2','3','4']

for k,v in dict.items():
  if v == my_list[2]:
    print(k)

Outputs:

dogs
rabbits
viniciusdgc
  • 91
  • 1
  • 2