跳过包含某些键的字典

问题描述 投票:0回答:1

我正在寻找一种好方法来跳过多个不同字典中包含某些键的字典。

现在我正在字典对象上链接

.get()
方法并继续匹配任何匹配项,这是有效的,但有点混乱。

我正在做类似的事情:

...
if my_dict.get('some_key', my_dict.get('other_key', my_dict.get('some_other_key'))):
    continue

python dictionary
1个回答
2
投票

您可以将

any
与生成器表达式一起使用,该表达式迭代可能的键并测试字典是否具有任何键:

if any(key in my_dict for key in ('some_key', 'other_key', 'some_other_key')):
    continue

或者,您可以使用

set.isdisjoint
来测试该组键是否与 dict 键不相交:

if not {'some_key', 'other_key', 'some_other_key'}.isdisjoint(my_dict):
    continue
© www.soinside.com 2019 - 2024. All rights reserved.