简体   繁体   中英

Adding values to dictionary in Python

The code below:

rect_pos = {}

rect_pos_single = [[0,0], [50, 0], [50, 100], [0, 100]]

i = 0

while (i<3): 

    for j in range(4):

        rect_pos_single[j][0] += 50

    print rect_pos_single

    rect_pos[i] = rect_pos_single

    i += 1

print rect_pos

The code prints subsequent iterations of the variable "rect_pos_single". Next, I add them to dictionary "rect_pos". Keys change, but value is always the same - last iteration. I do not understand why?

This line

rect_pos_single[j][0] += 50

modifies the list in-place; that is, rect_pos_single always refers to the same list object, but you change the contents of that list.

This line

rect_pos[i] = rect_pos_single

assigns a reference to the list referenced by rect_pos_single to rect_pos[i] . Each element of rect_pos refers to the same list.

The simplest change is to assign a copy of the list to the dictionary with

rect_pos[i] = copy.deepcopy(rect_pos_single)  # Make sure you import the copy module

A deep copy is needed because rect_pos_single is a list of lists, and doing a shallow copy with rect_pos_single would simply create a new list with references to the same lists that are actually modified with rect_pos_single[j][0] += 50 .

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