Python 判断字典为空的3种方法

在 Python 中,判断一个字典是否为空是一项常见的任务。以下介绍三种简单有效的方法:

方法一:使用 bool() 函数pythonmy_dict = {}if bool(my_dict): print('字典不为空')else: print('字典为空')

空字典会被 bool() 函数转换为 False,非空字典则为 True

方法二:使用 len() 函数pythonmy_dict = {}if len(my_dict) > 0: print('字典不为空')else: print('字典为空')

len() 函数返回字典中键值对的数量。如果长度为 0,则字典为空。

方法三:使用 keys() 函数pythonmy_dict = {}if my_dict.keys(): print('字典不为空')else: print('字典为空

Python 判断字典为空的3种方法 - 简明教程

原文地址: https://www.cveoy.top/t/topic/faR5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录