首页 > 解决方案 > 所有键的字典值都会自动删除

问题描述

代码

 def fill_dictionary_with_valid_addr_row_data( df ):

        data_list = []
        dictionary = {}
        int_endianness = 0

        for i in df.index:
            addrstr = str(df['Address'][i])

            if (addrstr != 'nan'):

                try:
                    addr = int(addrstr, 16)

                except:
                    print("Address in excel is not in hex format : %s", addrstr)
                    sys.exit()

                width = int(df['Width'][i])
                width = int(width / 8);

                endianess = df['Endianess'][i]
                if (endianess != 'B') and (endianess != 'L'):
                    print("ERROR: Register endianess is not B or L");
                    print("Register : %x, Endianess : %s" % (addr, endianess))
                    sys.exit()

                if endianess == 'B':
                    int_endianness = 1

                data_list.append(addr)
                data_list.append(width)
                data_list.append(int_endianness)

                dictionary[i] = data_list
                print(dictionary)

                data_list.clear()

        print(dictionary)

        return dictionary

问题

当我在 for 循环中打印字典时,一切都很好。当我在 for 循环外打印字典时,所有值(列表)都是空的。

以下是日志

{0: [22216704, 4, 1]}
{0: [22216716, 4, 1], 5: [22216716, 4, 1]}
{0: [22216720, 4, 1], 5: [22216720, 4, 1], 7: [22216720, 4, 1]}
{0: [], 5: [], 38: [], 7: []}

我是一个初学者的python程序员。我试图通过互联网搜索很多,但我没有找到任何解决方案。

有什么线索吗?

标签: pythonpython-3.xdictionary

解决方案


每当您这样做dictionary[i] = data_list时,您实际上都会将列表的引用分配给字典条目。考虑以下示例:

>>> l = [1,2,3]
>>> d = {}
>>> d["a"] = l
>>> d["b"] = l
>>> d
{'a': [1, 2, 3], 'b': [1, 2, 3]}
>>> l.clear()
>>> d
{'a': [], 'b': []}

如您所见,更改l会反映在所有字典值中。您每次在打印输出中看到的是相同的列表分别分配给一个、两个或三个字典条目。因为它总是相同的值,看起来好像您每次都添加了不同的列表,但事实并非如此。

您真正想要做的是为每个循环迭代创建一个新列表:

for i in df.index:
    ...

    data_list = []
    data_list.append(addr)
    data_list.append(width)
    data_list.append(int_endianness)
    dictionary[i] = data_list

或更短:

dictionary[i] = [addr, width, int_endianness]

使用此代码data_list将在每次迭代中包含一个新列表,与之前定义的列表无关。


推荐阅读