首页 > 解决方案 > 当字典更改时,列表中的所有字典都会更改其值

问题描述

请帮我解决问题。

我创建一个列表。然后我附加到它的字典。在第二个字典附加后,我在列表中有 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'}

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

标签: listdictionaryrobotframework

解决方案


因为在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}

推荐阅读