python - 为什么我可以使用按位 AND 检查列表是否包含字典的键?

标签 python dictionary bit-manipulation

我偶然发现了这个问题Python - intersection between a list and keys of a dictionary ,不幸的是没有所需的声誉来询问:

为什么会这样?

d1 = {'200:200':{'foo':'bar'},'300:300':{'foo':'bar'}}
l1 = ['200:200', '90:728']
keys = d1.keys() & l1

最佳答案

d1.keys() 的结果是一个类似 View 的集合。

Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that (key, value) pairs are unique and hashable, then the items view is also set-like. (Values views are not treated as set-like since the entries are generally not unique.) For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^).

来自https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects

& 的第二个参数只需要是可哈希对象的可迭代对象(尽管文档中没有说明)。

参见https://docs.python.org/3/library/stdtypes.html#set.intersection

关于python - 为什么我可以使用按位 AND 检查列表是否包含字典的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32144787/

相关文章:

Python Pandas - 根据值是否出现在多天内分配字符串

python - 如何使用 Python key 环检索用户名?

python - 使用 setup.py 安装包的导入错误

swift - 如何在 Swift 4.1 中从字典中随机选择三个元素

ios - 将来自 JSON 字典字典的 http 请求中的数据转换为 Swift 中的一个字典数组

sql - 按位异或,在 SQL 中固定长度的二进制字符串(240 字节)

python - 随机翻转python二进制字符串中的位

python - 如何使用 python 访问 MTP USB 设备

python - 如何找到字典中哪个键具有最长的值列表?

python - Python中的二进制补码