我有下面两种字典列表,它们根据一些操作返回键值,我需要从中检查字典的类型
operation1 - test_dict=[{'name':['john','hari','ram'], 'id':['213','222','342']}]
operation2: test_dict=[{'name':'john', 'id':'213'}]
如果我检查两种情况的长度,它将返回1
print(len(test_dict))
#预期:我想根据返回的字典类型执行某些任务
if type (dict) that return == operation1:
do task1
else: ### that return == operation2
do task 2
如果有人能在这个上提供帮助,我将不胜感激
您可以这样检查:
遍历列表中的每个项,然后检查字典中的每个值是否为列表。如果字典中的所有值都是列表,那么它就是operation1(根据您的定义(,否则它就是operations2。
def check_operations(test):
if all(isinstance(v, list) for t in test for v in t.values()):
return 'operation1'
else:
return 'operation2'
test_dict=[{'name':['john','hari','ram'], 'id':['213','222','342']}]
print (check_operations(test_dict))
test_dict=[{'name':'john', 'id':'213'}]
print (check_operations(test_dict))
这是这个的输出:
operation1
operation2
如果您认为operation1可能至少有一个列表,则可以将If语句更改为any
而不是all
。使用all
,我正在检查字典中的所有值是否都是列表。