简体   繁体   中英

How to pass dictionary key as function argument in Python

I'm a python and programming beginner and I've been trying to create a function to check whether a given key exists inside a dictionary or not and retrun boolean. This topic was helpful but did not solve my function parameter problem. I found many topics related to passing a dictionary as argument in a function but none stating how to do so with a key, couldn't find an answer to my specific problem in here .

When I use my code inside the main program, it works fine:

if "myKey" in myDict:
    answ = True
    print(myKey, " is there!")
else:
    answ = False
    print(myKey, " is not there.")

However, trying to make a function of it and then calling it doesn't work, it doesn't return an error either, just nothing happens nor gets printed.

def checkIfThere(myKey, myDict):
    #for i in myDict:
        if myKey in myDict:
            return True
            print(myKey, "is there!")
        else:
            return False
            print(myKey, "is not there.")

That I've tried calling with the following:

checkIfThere("thisIsAKey", myDict)
checkIfThere(thisIsAKey, myDict)
checkIfThere("\"thisIsAKey\"", myDict)

What am I missing? Is it just not feasible to pass a dictionary key as argument to a function?

The problem is that your function will stop execution, and return control to the caller , when it encounters a return statement. Note, you are also discarding the return value (since you don't assign the result of the call to a variable).

Consider:

>>> def some_func(x):
...     return
...     print(x)
...
>>> y = some_func(42)

Notice, the print function never ran.

Generally, you should let the function do the work, and let the caller do the printing. So, your function could be written (in a more streamlined manner):

>>> def check_if_there(key, adict):
...     return key in adict
...
>>> is_in = check_if_there('a', {'b':2})
>>> print(is_in)
False

Notice, this function's responsibility is simply to check if a key in a dict. As you learn to program, you will find it useful to split functions into re-usable, composable parts. So, another function could have the reponsibility of printing:

>>> def tell_if_there(key, adict):
...     if check_if_there(key, adict):
...         print(key, " is there!")
...     else:
...         print(key, " is not there.")
...
>>> tell_if_there('a', {'b':2})
a  is not there.
>>> tell_if_there('b', {'b':2})
b  is there!

Your functions works fine!

But the print statement should be outside of the function. Try this.

1) Define your function without print statement

def checkIfThere(myKey, myDict):  
    for i in myDict:  
        if myKey in myDict:  
            return True  
        else:  
            return False

This will return True or False depending on myKey is one of the keys of myDict.

2) Then, run the followings.

if checkIfThere(myKey, myDict):  
    print(myKey, " is there!")  
else:  
    print(myKey, " is not there.")

This will print myKey is there if the function above returns True; otherwise myKey is not there.

Thank you.

The problem with your function is that you are returning from the function before printing anything.

You could remove the return statement from your function in order to make it work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM