2014-08-28 232 views
0

我遇到這個奇怪的問題今天早上來的?怪異蟒蛇字典augement分配

+4

無法複製。 – 2014-08-28 02:26:07

+2

我不認爲你在發佈你實際使用的代碼。 – BrenBarn 2014-08-28 02:27:42

+0

對不起,我用了dict.fromkeys函數,我想我正在關閉原因 – yorua007 2014-08-28 02:29:19

回答

4

dict.fromkeys創建了一大堆引用的列表。換句話說,d['a']d['b']等當你做+=你擴大名單到位,所以在所有列表中看到修改 - 畢竟,他們是相同的列表。

>>> l = ['a', 'b', 'c'] 
>>> d = dict.fromkeys(l, []) 
>>> d 
{'a': [], 'c': [], 'b': []} 
>>> print [id(v) for v in d.values()] # Note, they all have the same ID -- They're the same. 
[4385936016, 4385936016, 4385936016] 
>>> d['a'] += [1] 
>>> d 
{'a': [1], 'c': [1], 'b': [1]} 

正如在評論中指出,我其實並沒有告訴你如何解決這個問題。如果你想初始化是可變值的情況下鍵的字典,你可以使用字典解析:

d = {key: [] for key in l} 

或者,如果你堅持使用舊版本的Python(python2.7之前)你傳遞產生2元組的字典構造一個迭代:

d = dict((key, []) for key in l) 

注意,有以及其他變體是瞭解(colections.defaultdict,常規字典子與重寫__missing__)是有用的。其中每個都有稍微不同的行爲,我會解釋here。然而,這應該是足以讓你去暫且...

+0

海報試圖做的正確表示法是'dict = {key:[] for key in l}',爲每個鍵設置自己的唯一列表,我不想在發佈新的答案時你已經釘上了它。 – user2085282 2014-08-28 02:36:24

+0

@ user2085282 - 好點。我想我應該提供一個替代方案。 。 。 – mgilson 2014-08-28 05:14:18

0

您可能會感興趣的collections.defaultdict:

In [66]: d = collections.defaultdict(list) 

In [67]: d['a'] += [1] 

In [68]: d 
Out[68]: defaultdict(<class 'list'>, {'a': [1]}) 

In [69]: dict(d) 
Out[69]: {'a': [1]} 

In [70]: d['b'] 
Out[70]: [] 

In [71]: dict(d) 
Out[71]: {'b': [], 'a': [1]} 

In [72]: d['c'] 
Out[72]: [] 

In [73]: dict(d) 
Out[73]: {'b': [], 'c': [], 'a': [1]}