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.