在 Python 中检查字典中是否有多个键
Check if multiple Keys are in a Dictionary in Python
检查字典中是否有多个键:
- 使用生成器表达式迭代包含键的元组。
- 使用
in
运算符检查每个键是否在字典中。 - 将结果传递给
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')
我们将要测试的多个键包装在一个
tuple, and used a generator expression to iterate over the
元组中。
在每次迭代中,我们使用in
运算符检查字典中是否存在当前键。
in 运算符
测试成员资格。
例如,如果是 的成员,则k in d
计算为 ,否则计算为。True
k
d
False
dict
。my_dict = { 'name': 'Alice', 'country': 'Austria', 'age': 30 } print('name' in my_dict) # 👉️ True print('another' in my_dict) # 👉️ False
最后一步是将generator
对象传递给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
对象。
Check if multiple Keys are in a Dictionary using set #
To check if multiple keys are in a dictionary:
- Wrap the keys in a
set
object. - Use the
dict.keys()
method to get a view of the dictionary’s keys. - Check if the multiple keys are present in the view of the dictionary’s keys.
my_dict = { 'name': 'Alice', 'country': 'Austria', 'age': 30 } if {'name', 'country'} <= my_dict.keys(): # 👇️ this runs print('multiple keys are in the dictionary')
We used curly braces to add the keys as elements to a set
object.
The benefit of using a set is that we can check if the elements in the set
are
a subset of another sequence, e.g. a view of the dictionary’s keys.
The dict.keys
method returns a new view of the dictionary’s keys.
my_dict = { 'name': 'Alice', 'country': 'Austria', 'age': 30 } # 👇️ dict_keys(['name', 'country', 'age']) print(my_dict.keys())
小于或等于符号<=
检查set
对象是否是字典键视图的子集。
my_dict = { 'name': 'Alice', 'country': 'Austria', 'age': 30 } if {'name', 'country'} <= my_dict.keys(): # 👇️ this runs print('multiple keys are in the dictionary')
using 的替代方法<=
是使用该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方法测试的
每个元素是否set
在提供的序列中。