字典更改时,列表中的所有词典都会更改其值

时间:2018-06-25 21:19:17

标签: list dictionary robotframework

请帮助我解决问题。

我创建一个列表。然后我将其附加到字典上。在第二个附加字典之后,列表中有2个相同的字典,在第三个附加字典之后,列表中有3个相同的字典。

*** Settings ***
Library  Collections

*** Variables ***
&{test_dictionary}
@{positions_list}

*** Test Cases ***
Compaund list
    set to dictionary  ${test_dictionary}  Name=First Name  Length=50  db_name=f_name
    Append the dictionary to the list
    set to dictionary  ${test_dictionary}  Name=Last Name  Length=60  db_name=l_name
    Append the dictionary to the list
    set to dictionary  ${test_dictionary}  Name=Email Address  Length=40  db_name=email
    Append the dictionary to the list

*** Keywords ***
Append the dictionary to the list
    log dictionary  ${test_dictionary}
    append to list  ${positions_list}  ${test_dictionary}
    log list  ${positions_list}

所以,测试后我有一个奇怪的清单:

List length is 3 and it contains following items:
0: {'Name': 'Email Address', 'Length': '40', 'db_name': 'email'}
1: {'Name': 'Email Address', 'Length': '40', 'db_name': 'email'}
2: {'Name': 'Email Address', 'Length': '40', 'db_name': 'email'}

为什么要替换第一词典和第二词典?

1 个答案:

答案 0 :(得分:3)

因为在python中,变量(大致放置)是指向内存位置的指针;而字典是可变对象-例如您可以更改该内存位置中的值。

将其附加到列表后,列表元素将变为“该对象,指向该内存地址”,而不是您可能认为的“该对象的转储,作为新的内存位置”。然后您更改字典的值-例如内存地址中的值。而且,列表成员也更改了它-它仍然指向相同的内存地址,现在具有不同的值。

如果您希望列表在列表中有3个不同的字典,请使用3个变量。

或者,如果您不想这样做,请在字典的副本列表中存储;作为副本,如果原始副本不变,则不会更改

*** Settings ***
Library  Collections

*** Variables ***
&{test_dictionary}
@{positions_list}

*** Test Cases ***
Compaund list
    set to dictionary  ${test_dictionary}  Name=First Name  Length=50  db_name=f_name
    Append the dictionary to the list
    set to dictionary  ${test_dictionary}  Name=Last Name  Length=60  db_name=l_name
    Append the dictionary to the list
    set to dictionary  ${test_dictionary}  Name=Email Address  Length=40  db_name=email
    Append the dictionary to the list

*** Keywords ***
Append the dictionary to the list
    &{dict_copy}=    Copy Dictionary    ${test_dictionary}
    log dictionary  ${dict_copy}
    append to list  ${positions_list}  ${dict_copy}
    log list  ${positions_list}