在python中,作为参数在函数之间传递字典?

2024-03-29 14:50:07 发布

您现在位置: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...

是的。你知道吗

但我以为我已经传递了变量。。。?那么为什么{}看起来优先于虚拟的测试?你知道吗

至于我想做什么。。。。你知道吗

1)将名为fridge的字典作为第一个参数传递给函数。使用isinstance和type error确认字典确实是字典。你知道吗

2)有第二个功能,将从冰箱字典中减去


Tags: of函数test参数return字典defeggs
2条回答

注:{"cheese", "milk", "eggs"}是一个集合。你知道吗

在第一个函数中,只需返回参数,因此得到的结果也就不足为奇了。在第二种方法中,在返回之前将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()方法验证了dict之后得到了dict。例如:

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

所以:

print(validation["cheese"])

输出:

10

此外:

print(validation["milk"])

输出:

11

其他的就这样。总之,为了从dict中减去值,可以使用:dictionary["key"]这将输出键的值。你知道吗

另外,我建议您阅读本文tutorial,以了解如何处理python dicts。你知道吗

相关问题 更多 >