簡體   English   中英

如何在Python中將字典鍵作為函數參數傳遞

[英]How to pass dictionary key as function argument in Python

我是python和程序設計的初學者,我一直在嘗試創建一個函數來檢查給定鍵是否在字典中,然后重新運行布爾值。 這個主題很有幫助,但沒有解決我的函數參數問題。 我發現了許多與將字典作為參數傳遞給函數有關的主題,但是沒有一個主題說明如何使用鍵來實現,在這里找不到我特定問題的答案。

當我在主程序中使用代碼時,它可以正常工作:

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

但是,嘗試使其功能然后調用它不起作用,它也不會返回錯誤,什么也不會發生,也不會被打印出來。

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.")

我嘗試用以下命令進行調用:

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

我想念什么? 將字典鍵作為參數傳遞給函數只是不可行嗎?

問題在於您的函數將停止執行, 在遇到return語句時將控制權返回給調用方 注意,您也將丟棄返回值(因為您沒有將調用結果分配給變量)。

考慮:

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

注意, print功能從未運行過。

通常,應該讓函數完成工作,然后讓調用者進行打印。 因此,可以編寫函數(以更簡化的方式):

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

注意,此功能的職責只是檢查字典中是否有鍵。 在學習編程時,您會發現將功能拆分為可重用,可組合的部分很有用。 因此,另一個功能可能具有打印的責任:

>>> 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!

您的功能正常!

但是print語句應該在函數之外。 嘗試這個。

1)在沒有打印語句的情況下定義函數

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

這將返回True或False,具體取決於myKey是myDict的鍵之一。

2)然后,運行以下程序。

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

如果上面的函數返回True,將打印myKey在那里; 否則myKey不存在。

謝謝。

函數的問題是您要在打印任何內容之前從函數返回。

您可以從函數中刪除return語句以使其起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM