Python可变set用于字典构造与文档描述矛盾的疑问
Great question! Let's break this down clearly—you're not contradicting the Python docs, you're just using sets in a different way than the warning describes.
First, let's restate the docs' rule clearly
set type is mutable .... Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set
This rule applies when you try to use the set object itself in a context that requires hashability. For example, if you run this code:
my_dict = {set([1, 2]): "test value"}
You'll get the expected error: TypeError: unhashable type: 'set'—this is exactly the scenario the docs are warning about.
Now let's unpack your examples
Your code isn't using the set as a dictionary key—it's using the set as an iterable source of values that become dictionary keys:
dict(zip(set(['a', 'b', 'c']), [1, 2, 3]))
Thezip()function iterates over the set, pulling out each element ('a','b','c') and pairing them with elements from the list. This creates a sequence of tuples like('a', 1),('b', 2), etc. Thedict()constructor then converts these tuples into key-value pairs. The set itself never becomes a key—its elements do.dict.fromkeys(set([1, 2, 3, 4]))
Thefromkeys()method takes an iterable, iterates over it, and uses each element as a dictionary key (with a default value ofNone). Again, we're only using the elements of the set as keys, not the set object itself.
The core distinction
Mutability only prevents the set from being used directly as a hashable entity (like a key or set element). It doesn't stop the set from being iterated over to extract its elements—many of which (like strings, integers, tuples) are hashable and perfectly valid as dictionary keys.
内容的提问来源于stack exchange,提问作者Wira Bhakti

