在Dictionary键上使用set

mrQ*_*RTY 2 python dictionary list set

对于我的程序,我希望仔细检查列表中的任何元素是否是字典中的键.到目前为止,我只能考虑遍历列表并进行检查.

但是,有没有办法简化这个过程?有没有办法使用套装?通过集合,可以检查两个列表是否具有共同元素.

mgi*_*son 5

使用内置any函数应该很容易:

any(item in dct for item in lst)
Run Code Online (Sandbox Code Playgroud)

这是快速,有效和(恕我直言)相当可读.还有什么比这更好的?:-)


当然,这并不能告诉你哪些键在dict中.如果您需要,那么您最好的办法是使用字典视图对象:

 # python2.7
 dct.viewkeys() & lst  # Returns a set of the overlap

 # python3.x
 dct.keys() & lst  # Same as above, but for py3.x
Run Code Online (Sandbox Code Playgroud)