来自 dict.fromkeys 的不良行为 [英] Unwanted behaviour from dict.fromkeys
问题描述
我想使用 dict.fromkeys
初始化一个集合字典(在 Python 2.6 中),但结果结构的行为很奇怪.更具体地说:
我显然不想在所有集合中添加 3,只想添加到 x[5]
对应的集合中.当然,我可以通过在没有 fromkeys
的情况下初始化 x
来避免这个问题,但我想了解我在这里遗漏了什么.
dict.fromkeys
的第二个参数只是一个值.您已经创建了一个字典,该字典将 same 设置为每个键的值.大概你了解它的工作方式:
你在那里看到了同样的行为;在您的情况下,x[0]
、x[1]
、x[2]
(等)都是访问确切信息的不同方式相同的 set
对象.
对于字符串表示形式包括其内存地址的对象,这更容易看到,您可以在其中看到它们是相同的:
<预><代码>>>>dict.fromkeys(range(2), object()){0:<0x1001da080 处的对象对象>,1:<0x1001da080处的对象>}I'd like to initialise a dictionary of sets (in Python 2.6) using dict.fromkeys
, but the resulting structure behaves strangely. More specifically:
>>>> x = {}.fromkeys(range(10), set([]))
>>>> x
{0: set([]), 1: set([]), 2: set([]), 3: set([]), 4: set([]), 5: set([]), 6: set([]), 7: set([]), 8: set([]), 9: set([])}
>>>> x[5].add(3)
>>>> x
{0: set([3]), 1: set([3]), 2: set([3]), 3: set([3]), 4: set([3]), 5: set([3]), 6: set([3]), 7: set([3]), 8: set([3]), 9: set([3])}
I obviously don't want to add 3 to all sets, only to the set that corresponds to x[5]
. Of course, I can avoid the problem by initialising x
without fromkeys
, but I'd like to understand what I'm missing here.
The second argument to dict.fromkeys
is just a value. You've created a dictionary that has the same set as the value for every key. Presumably you understand the way this works:
>>> a = set()
>>> b = a
>>> b.add(1)
>>> b
set([1])
>>> a
set([1])
you're seeing the same behavior there; in your case, x[0]
, x[1]
, x[2]
(etc) are all different ways to access the exact same set
object.
This is a bit easier to see with objects whose string representation includes their memory address, where you can see that they're identical:
>>> dict.fromkeys(range(2), object())
{0: <object object at 0x1001da080>,
1: <object object at 0x1001da080>}
这篇关于来自 dict.fromkeys 的不良行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!