Python: Why does listA.append ('a') affect listB?

This is my code:

In [8]: b=dict.fromkeys([1,2,3,4], [])

In [9]: b[1].append(1)

In [10]: b[2].append(2)

In [11]: b[1]
Out[11]: [1, 2]

In [12]: b[2]
Out[12]: [1, 2]

In [13]: b
Out[13]: {1: [1, 2], 2: [1, 2], 3: [1, 2], 4: [1, 2]}

While I would expect: {1: [1], 2: [2], 3: [], 4: []}

I assume that this may be caused by b [X] - this is just a “link”, they all refer to the same list.

Then I replace [] with an int object. The result confuses me:

In [15]: b=dict.fromkeys([1,2,3,4], 1)

In [16]: b[1] += 1

In [17]: b[2] += 1

In [18]: b
Out[18]: {1: 2, 2: 2, 3: 1, 4: 1}

This int 1 object is not a reference in this case.

Then I replace [] with ['a']:

In [19]: b=dict.fromkeys([1,2,3,4], ['a'])

In [20]: b[1].append(1)

In [21]: b[2].append(2)

In [22]: b
Out[22]: {1: ['a', 1, 2], 2: ['a', 1, 2], 3: ['a', 1, 2], 4: ['a', 1, 2]}

Now ['a'] is referencing again.

Can someone tell me why and how to get the expected result "{1: [1], 2: [2], 3: [], 4: []}" in the first case.

Any helpful suggestions are welcome.

+4
source share
2 answers

dict , dict.fromkeys . list.append , .

>>> b = dict.fromkeys([1,2,3,4], [])
>>> [id(x) for x in b.values()]
[158948300, 158948300, 158948300, 158948300]

, dict:

>>> b = {k:[] for k in xrange(1, 5)}
>>> [id(x) for x in b.values()]
[158945580, 158948396, 158948108, 158946764]

, @Bakuriu, collections.defaultdict :

>>> from collections import defaultdict
>>> dic = defaultdict(list)
>>> dic[1].append(1)
>>> dic[2].append(2)
>>> dic
defaultdict(<type 'list'>, {1: [1], 2: [2]})
>>> dic[3]
[]
+6

. , .

=, . (+= ).

append, , . fromkeys , .

+4

All Articles