繁体   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