首页 > 解决方案 > Python如何检查/比较返回单个或多个值的字典列表类型

问题描述

我有以下两种字典列表,它们根据某些操作返回键值,我需要从中检查字典的类型

operation1 - test_dict=[{'name':['john','hari','ram'], 'id':['213','222','342']}]

operation2: test_dict=[{'name':'john', 'id':'213'}]

如果我检查两种情况的长度,它将返回 1

print(len(test_dict))

#Expected:我想根据返回的字典类型执行某些任务

if type (dict) that return == operation1:
  do task1
else:            ### that return == operation2
  do task 2  

感谢是否有人可以提供帮助

标签: python-3.xdictionary

解决方案


您可以像这样检查它:

遍历列表中的每个项目,然后检查字典中的每个值是否是列表。如果字典中的所有值都是列表,那么它是 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,我正在检查字典中的所有值是否都是列表。


推荐阅读