简体   繁体   中英

python append and += problem with dict

this seems really simple but I don't know what I got wrong.

d1 = dict(zip(range(10), [[]]*10))
l1 = zip(range(10), range(10,20))

for pair in l1:
    d1[pair[0]].append(pair)

resulting d1:

>>> d1
{0: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 1: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 2: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 3: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 4: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 5: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 6: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 7: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 8: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 9: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)]}

with this:

for pair in l1:
    d1[pair[0]] += [pair]

the same thing, but with:

for pair in l1:
    d1[pair[0]] = d1[pair[0]] + [pair]

it gives me the desired result which is

>>> d1
{0: [(0, 10)], 1: [(1, 11)], 2: [(2, 12)], 3: [(3, 13)], 4: [(4, 14)], 5: [(5, 15)], 6: [(6, 16)], 7: [(7, 17)], 8: [(8, 18)], 9: [(9, 19)]}

seem's I miss something basic in the syntax, could anyone kindly point it out? thanks~

Alex

Don't use multiplication with mutable objects. It gives you X references to the object, not X different objects.

d1 = dict((idx, []) for idx in range(10))

Instead of [[]]*10 , you should use

[[] for i in range(10)]

as the first one just makes a list of elements that point to a single array reference.

Example

>>> d1 = dict(zip(range(10), [[] for i in range(10)]))
>>> l1 = zip(range(10), range(10,20))
>>>
>>> for pair in l1:
...     d1[pair[0]].append(pair)
...
>>> d1
{0: [(0, 10)], 1: [(1, 11)], 2: [(2, 12)], 3: [(3, 13)], 4: [(4, 14)], 5: [(5, 1
5)], 6: [(6, 16)], 7: [(7, 17)], 8: [(8, 18)], 9: [(9, 19)]}
>>>
>>> d1
{0: [(0, 10)], 1: [(1, 11)], 2: [(2, 12)], 3: [(3, 13)], 4: [(4, 14)], 5: [(5, 1
5)], 6: [(6, 16)], 7: [(7, 17)], 8: [(8, 18)], 9: [(9, 19)]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM