So I have to make a function called "test" with 3 parameters(int, bool, dict) and the bool is set to True and the dict is {2:3, 4:5, 6:8}. So if bool is True then test to see if int is in dict. If it is then return the value, if not return False. Also the boolean and dict are optional parameters, I don't know if that changes anything. This is my question: Write a function, test, that takes in three parameters: a required integer, an optional boolean whose default value is True, and an optional dictionary, called dict1, whose default value is {2:3, 4:5, 6:8}. If the boolean parameter is True, the function should test to see if the integer is a key in the dictionary. The value of that key should then be returned. If the boolean parameter is False, return the boolean value “False”

def test(x, abool = True, dict1 = {2:3, 4:5, 6:8}):
    if abool == True:
        if x in dict1:
            return x
    else:
        return False

2 Answers

0
Community On Best Solutions
if x in dict1:
    return X

This will check whether the key is in the dictionary and then return the key, not the value like you want.

It could look like this:

if x in dict1:
    return dict1[X]

If the key is in the dictionary, return the corresponding value.

Alternatively, you can use the dict.get(key[, default]) method.

return abool and dict1.get(x, False)

This will check if x is in the dictionary. If not, it'll return default (False in this case). If it is, it returns the corresponding value.

0
Nathan On

First off, it's not 100% clear what you want or what is wrong. I suggest you look here. That being said, it seems you want to return the value of the dict instead of the key. To do this you need to call:

return dict1[x]

instead of

return x