Python检查函数参数是否为dict并且有值

2024-06-26 03:26:56 发布

您现在位置:Python中文网/ 问答频道 /正文

这里我有下面的函数和列表

def prdata(somelist):
    if all(x != None for x in list1.values()): 
    #check list have values 
    #but gives me error for list1 AttributeError: 'set' object has no attribute 'values'
        for x in somelist:
            print(somelist[x])
    else:
        # print("invalid dict")

我的输入可能如下所示

list1 = {"a", "b", "c"}
prdata(list1)

list2 = {"a": 1, "b": 2, "c": 3}
prdata(list1)

如何检查内部函数并提出正确的错误


Tags: 函数innone列表forifdefcheck
3条回答

你的代码

list1 = {"a", "b", "c"}

这不是单子也不是字典。这是set

all(x != None for x in list1.values())

集合没有方法值。也许可以直接迭代集合元素。你知道吗

list1设置在list2是字典的地方

在list1的情况下,您需要更改代码,如下所示-

list1 = {"a", "b", "c"}
all(x != None for x in list1)

这是真的

list1是一个集合而不是dict。要测试集合中的成员身份,只需使用“x in list1”。你知道吗

相关问题 更多 >