You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python可变set用于字典构造与文档描述矛盾的疑问

Why can mutable sets be used to construct dictionaries?

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:

  1. dict(zip(set(['a', 'b', 'c']), [1, 2, 3]))
    The zip() 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. The dict() constructor then converts these tuples into key-value pairs. The set itself never becomes a key—its elements do.

  2. dict.fromkeys(set([1, 2, 3, 4]))
    The fromkeys() method takes an iterable, iterates over it, and uses each element as a dictionary key (with a default value of None). 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:26:19