迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中检查字典中是否有多个键

作者:迹忆客 最近更新:2022/12/25 浏览次数:

检查字典中是否有多个键:

  1. 使用生成器表达式迭代包含键的元组。
  2. 使用 in 运算符检查每个键是否在字典中。
  3. 将结果传递给 all() 函数。
my_dict = {
    'name': 'Alice',
    'country': 'Austria',
    'age': 30
}

# ✅ check if multiple keys in dict using all()

if all(key in my_dict for key in ("name", "country")):
    # 👇️ this runs
    print('multiple keys are in the dictionary')

# ----------------------------------------------

# ✅ check if multiple keys in dict using set object

if {'name', 'country'} <= my_dict.keys():
    # 👇️ this runs
    print('multiple keys are in the dictionary')

Python 中检查字典中是否有多个键

我们将要测试的多个键包装在一个元组中,并使用生成器表达式迭代元组。

生成器表达式用于对每个元素执行某些操作或选择满足条件的元素子集。

在每次迭代中,我们使用 in 运算符来检查字典中是否存在当前键。

in 运算符测试成员资格。 例如,如果 k 是 d 的成员,则 k in d 的计算结果为 True,否则计算结果为 False

与字典一起使用时,运算符会检查字典对象中是否存在指定键。

my_dict = {
    'name': 'Alice',
    'country': 'Austria',
    'age': 30
}

print('name' in my_dict)  # 👉️ True

print('another' in my_dict)  # 👉️ False

最后一步是将生成器对象传递给 all() 函数。

my_dict = {
    'name': 'Alice',
    'country': 'Austria',
    'age': 30
}


if all(key in my_dict for key in ("name", "country")):
    # 👇️ this runs
    print('multiple keys are in the dictionary')

all() 内置函数将可迭代对象作为参数,如果可迭代对象的所有元素都为真(或可迭代对象为空),则返回 True

如果字典中存在所有键,则 all() 函数将返回 True,否则返回 False

my_dict = {
    'name': 'Alice',
    'country': 'Austria',
    'age': 30
}

# 👇️ True
print(all(key in my_dict for key in ('name', 'country')))

# 👇️ False
print(all(key in my_dict for key in ('another', 'country')))

或者,我们可以使用集合对象。


使用 set 检查字典中是否有多个键

检查字典中是否有多个键:

  1. 将键包装在一个集合对象中。
  2. 使用 dict.keys() 方法来查看字典的键。
  3. 检查字典键的视图中是否存在多个键。
my_dict = {
    'name': 'Alice',
    'country': 'Austria',
    'age': 30
}


if {'name', 'country'} <= my_dict.keys():
    # 👇️ this runs
    print('multiple keys are in the dictionary')

我们使用花括号将键作为元素添加到集合对象中。

集合对象是唯一元素的无序集合

使用集合的好处是我们可以检查集合中的元素是否是另一个序列的子集,例如 字典键的视图。

dict.keys 方法返回字典键的新视图。

my_dict = {
    'name': 'Alice',
    'country': 'Austria',
    'age': 30
}

# 👇️ dict_keys(['name', 'country', 'age'])
print(my_dict.keys())

小于或等于符号 <= 检查集合对象是否是字典键视图的子集。

my_dict = {
    'name': 'Alice',
    'country': 'Austria',
    'age': 30
}


if {'name', 'country'} <= my_dict.keys():
    # 👇️ this runs
    print('multiple keys are in the dictionary')

使用 <= 的替代方法是使用 set.issubset() 方法。

my_dict = {
    'name': 'Alice',
    'country': 'Austria',
    'age': 30
}


if {'name', 'country'}.issubset(my_dict.keys()):
    # 👇️ this runs
    print('multiple keys are in the dictionary')

set.issubset 方法测试集合中的每个元素是否都在提供的序列中。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便