Python 判断字典中 key 是否存在(三种方式)

简介: Python 判断字典中 key 是否存在(三种方式)
  • 方式一:has_key(),在 python2.2 之前已经被放弃,所以推荐使用其他方式。
dict = { 'name': 'dzm', 'age': '20' }
print(dict.has_key('name')) # True
print(dict.has_key('id'))   # False
  • 方式二:keys(),需要 in 配合使用,也可以使用 not in
dict = { 'name': 'dzm', 'age': '20' }
print('name' in dict.keys())    # True
print('id' in dict.keys())      # False
print('id' not in dict.keys())  # True
  • 方式三:innot in【推荐使用】
dict = { 'name': 'dzm', 'age': '20' }
print('name' in dict)    # True
print('id' in dict)      # False
print('id' not in dict)  # True
相关文章
|
14天前
|
存储 Python 容器
python字典的常用操作方法
python字典的常用操作方法
|
15天前
|
存储 JSON JavaScript
使用 Python 将字典转换为 JSON
【8月更文挑战第27天】
14 2
|
21天前
|
存储 索引 Python
六:《Python基础语法汇总》— 字典和序列操作
本篇文章讲解了对字典元素的索引,以及字典常用的方法和函数;对字典的遍历;字典推导式和关于序列的运算符及方法
14 2
|
13天前
|
存储 数据库 Python
Python 中的字典是什么?
【8月更文挑战第29天】
13 0
|
14天前
|
Python
python在列表、元素、字典、集合和numpy的数组前加上星号 * 是什么含义,以及*args和**kwargs的使用
python在列表、元素、字典、集合和numpy的数组前加上星号 * 是什么含义,以及*args和**kwargs的使用
22 0
|
18天前
|
API 网络安全 开发工具
【Azure Developer - 密钥保管库 】使用 Python Azure SDK 实现从 Azure Key Vault Certificate 中下载证书(PEM文件)
【Azure Developer - 密钥保管库 】使用 Python Azure SDK 实现从 Azure Key Vault Certificate 中下载证书(PEM文件)
|
18天前
|
Python
合并两个 Python 字典
【8月更文挑战第24天】
11 0
|
18天前
|
存储 安全 API
【Azure Developer】Python代码通过AAD认证访问微软Azure密钥保管库(Azure Key Vault)中机密信息(Secret)
【Azure Developer】Python代码通过AAD认证访问微软Azure密钥保管库(Azure Key Vault)中机密信息(Secret)
|
19天前
|
存储 安全 API
【Azure Developer】Python代码通过AAD认证访问微软Azure密钥保管库(Azure Key Vault)中机密信息(Secret)
【Azure Developer】Python代码通过AAD认证访问微软Azure密钥保管库(Azure Key Vault)中机密信息(Secret)
|
4月前
|
存储 Python
python字典中删除键值的方法
python字典中删除键值的方法
141 0