簡體   English   中英

在python中的函數之間傳遞字典作為參數?

[英]passing of a dictionary as a parameter between functions in python?

我正在嘗試將字典傳遞給函數,以便它是函數的第一個參數,並且進行類型檢查以確認確實提交了字典。

fridge = {"cheese":10, "milk":11, "feta":12, "cream":21, "onion":32, "pepper":14}

def fridge_validation(fridge):
    if not isinstance (fridge,dict) :
        raise TypeError: ("require a valid dictionary to be submitted!")

我認為以下方法會起作用。

def dummy (fridge):

return fridge

test_of_dummy=dummy ({"cheese", "milk", "eggs"})

print (test_of_dummy)

{'eggs', 'milk', 'cheese'} (this was what was printed)

不確定我是否正確完成了操作? 另外...以下內容使我感到困惑。

 def dummy (fridge):
    fridge={}
    return fridge





  test_of_dummy=dummy ({"cheese", "milk", "eggs"})
    print (test_of_dummy) "{}" was outputted...

但我以為我已經傳遞了變量...? 那么,為什么{}似乎優先於test_of_dummy?

至於我要做什么...

1)將名為冰箱的字典作為第一個參數傳遞給函數。 使用isinstance和類型錯誤來確認字典確實是字典。

2)有第二個功能將從冰箱詞典中減去

注意: {"cheese", "milk", "eggs"}是一組。

在第一個函數中,您只返回了參數,因此得到的結果也就不足為奇了。 在第二個fridge ,您將fridge設置為空集,然后再將其退回,因此您將獲得一個空集。

但是,所有這些似乎都沒有必要,您到底要做什么,這意味着您只能操作一次字典?

為了驗證您的fridge變量,您可以按照以下示例操作:

fridge = {"cheese":10, "milk":11, "feta":12, "cream":21, "onion":32, "pepper":14}

def fridge_validation (fridge = {}):
    # Test if fridge is a dict type
    if not isinstance(fridge, dict):
        # if fridge isn't a dict type, throw an exception
        raise TypeError("require a valid dictionary to be submitted!")
    # if fridge is a dict type return it. So you got your validation
    else:
        return fridge

validation = fridge_validation(fridge)
print(validation)

輸出:

{'milk': 11, 'feta': 12, 'onion': 32, 'cheese': 10, 'pepper': 14, 'cream': 21}

但是, {"cheese", "milk", "eggs"}set type而不是dict type

您可以使用Python interpreter進行驗證:

>> a = {"cheese", "milk", "eggs"}
>> type(a)
<class 'set'>

因此,如您所見, {"cheese", "milk", "eggs"}是一個set而不是dict 因此,如果將其傳遞給您的fridge_validation()代碼將引發異常。

另外,在您的方法中:

def dummy(fridge):
    fridge = {}
    return fridge

返回值將始終等於{} ,這是一個空的dict type ,原因是您的代碼將始終被一個空的dict覆蓋您的冰箱值。

您第二個問題的答案。

如何從字典中減去值? 答案很簡單:

我想您在用fridge_validation()方法進行了驗證之后得到了一個字典。 例如:

validation = {"cheese":10, "milk":11, "feta":12, "cream":21, "onion":32, "pepper":14}

所以:

print(validation["cheese"])

輸出:

10

也:

print(validation["milk"])

輸出:

11

其余的依次類推。 總而言之,為了從字典中減去值,可以使用: dictionary["key"]這將輸出鍵的值。

另外,我建議您閱讀本教程 ,以了解如何處理python dicts

暫無
暫無

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

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