【发布时间】:2020-02-15 12:22:53
【问题描述】:
当我在字典上使用 set 时遇到这种行为时,我正在尝试一些想法来解决一个不相关的问题:
a = {"a": 1}
b = {"b": 2}
c = {"a": 1}
set([a, b, c])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-21-7c1da7b47bae> in <module>
----> 1 set([a, b, c])
TypeError: unhashable type: 'dict'
d = {"a": 1, "b": 2}
set(d)
Out[23]: {'a', 'b'}
set(a)
Out[24]: {'a'}
我有点理解为什么这组字典是不可散列的(它们是可变的),但整个事情对我来说没有那么大的意义。为什么set(a) 和set(d) 只返回键,这有什么用?
谢谢!
【问题讨论】:
-
好吧,如果您需要一个
set的键...请注意,list(a)同样会返回一个键列表,并且迭代 dict 会迭代其键。
标签: python dictionary set