You don't return anything if aller in listofallergies
, just print. Also, aller in listofallergies
will never be True, because that's not how you check if something is in the .values()
of a dict.
Returning None
is also not necessary if it is not in the dict — a function will return that automatically by default.
Since some_dict.keys()
doesn't take an argument, as you seem to assume, you will need to iterate over all values and check if they are equal to the given value.
Here's how you could fix it:
def allergie(aller):
listofallergies = {'eggs': 1 , 'peanuts':2 ,'shellfish': 4 , 'strawberries':8 , 'tomatoes': 16 , 'chocolat':32 , 'pollen': 64 , 'cats': 128 }
if aller in listofallergies.values():
for key, item in listofallergies.items():
if item == aller:
return key # we found it, so we return it.
Frankly, you could also skip checking if aller in listofallergies.values()
entirely, but maybe it's clearer this way.
If there's no good reason not to do this, why don't you just invert the dictionary? Then the function just becomes:
def allergie(aller):
return {1: "eggs", 2: "peanuts", 4: "shellfish", ...}.get(aller)
Finally, if this is indeed a bitmap, and you want to in fact return the list of allergies encoded in a given value, you can do so with bitwise arithmetics:
def allergies(allergy_code):
result = []
for index, allergy in enumerate(['eggs', 'peanuts','shellfish', 'strawberries', 'tomatoes', 'chocolat', 'pollen', 'cats']):
if allergy_code & 2**index:
result.append(allergy)
return result
>>> allergies(5)
['eggs', 'shellfish']