python-3.x - 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
感谢是否有人可以提供帮助
解决方案
您可以像这样检查它:
遍历列表中的每个项目,然后检查字典中的每个值是否是列表。如果字典中的所有值都是列表,那么它是 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
,我正在检查字典中的所有值是否都是列表。
推荐阅读
- perl - 为什么我的 Tie::IxHash 程序需要很长时间?
- ios - 在 WKWebView 中使用从网站启动的相机时在 Xamarin.Forms (iOS) 中获取 SIGABRT
- html - CSS - 如何控制固定位置
- r - 聚合多个时间序列
- python - 在 Python 中使用带有 break 语句逻辑的 any() 或 all()?
- c - 如果已经存在使用 FATFS 的文件,则在 sd 卡上创建另一个 txt 文件
- r - 使用自定义调色板和只有一个图例创建两层 geom_points
- javascript - => 在调用类方法并将 .then 链接到返回的内部函数时,指向 {} 会导致 TypeError:Undefined
. 为什么? - oracle - 将多个值从源表插入到目标表
- java - 获取所选recyclerView项目android的ID