将字典添加到带有联合的 `set()` [英] Add a dictionary to a `set()` with union
问题描述
我刚刚遇到了一些我想我会问的有趣的事情.
I just ran across something interesting that I thought I'd ask about.
将字典添加到 set
中,我曾假设该字典将作为完整字典添加,但事实并非如此.仅添加键:
Adding a dictionary to a set
, I had assumed that the dictionary would be added as a full dictionary, it isn't. Only the keys are added:
dicty = {"Key1": "Val1", "Key2": "Val2"}
setunion = set()
setunion.union(dicty)
=> set(['Key2', 'Key1'])
当您尝试使用 set.add()
添加它时,您会收到一个错误:
When you attempt to add it using set.add()
you get an error:
setadd = set()
setadd.add(dicty)
Traceback (most recent call last):
File "python", line 1, in <module>
TypeError: unhashable type: 'dict'
显然,这种行为与列表非常不同:
Obviously, this behaviour is very different from lists:
listy = []
listy.append(dicty)
listy
=> [{'Key2': 'Val2', 'Key1': 'Val1'}]
在文档中 它说集合是 hashable 对象的无序集合,这暗示了上面的一些问题.
In the docs it says that sets are unordered collections of hashable objects, which is a hint to some of the issues above.
这是怎么回事?设置项必须是可散列的,很明显这与为什么我只使用 .union()
将键添加到集合中有关,但是为什么 .add() 出现错误
?
What's going on here? Set items have to be hashable, so clearly that has to do with why I'm only adding the keys to the set with .union()
, but why the error with .add()
?
列表中集合的行为差异背后是否存在某些可用性原因?
Is there some usability reason behind the difference in behavior of sets from lists?
Python(或库)中是否有一种数据类型本质上类似于列表,但只保留唯一项?
Is there a datatype in Python (or a library) that essentially functions like a list, but only keeps unique items?
推荐答案
不,这是不可能的.哈希表(如dict
s 和set
s)进行查找的方式与数组(如list
s)进行查找的方式从根本上是独一无二的.逻辑错误是,如果您有一个只保存重复项的数据类型,如果您将其中一个元素变异为非唯一元素,会发生什么情况?
No that's impossible by definition. The way hash tables (like dict
s and set
s) do lookups is fundamentally unique from the way arrays (like list
s) do lookups. The logical error is that if you have a datatype that only saves duplicates, what happens if you mutate one of the elements to be non-unique?
a, b = [0], [0, 1]
s = SpecialSet(a, b)
a.append(1) # NOW WHAT?!
如果你想给一个集合添加一个字典,你可以添加它的 dict.items
视图(它实际上只是一个元组列表),但你必须先转换为元组.
If you want to add a dictionary to a set, you can add the dict.items
view of it (which is really just a list of tuples), but you have to cast to tuple first.
a = {1:2, 3:4}
s = set()
s.add(tuple(a.items()))
然后你必须重新转换为 dict 一旦它离开集合以取回字典
Then you'd have to re-cast to dict that once it leaves the set to get a dictionary back
for tup in s:
new_a = dict(tup)
在 PEP416 中提出了内置的 frozendict
类型但最终被拒绝.
A built-in frozendict
type was proposed in PEP416 but ultimately rejected.
这篇关于将字典添加到带有联合的 `set()`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!