更新字典的问题:所有键都有相同的列表



我在给字典赋值时遇到了问题。我希望使用for循环将一个变化列表(循环的每次迭代都会更新)分配给字典的键。但问题是所有键的列表最终都是相同的。

让我用一个例子来说明:

months = ['jan', 'feb', 'mar', 'apr']  # this is the list of keys of the Dictionary
numbers = []
sqrDict = {}
i = 1
for m in months:
numbers.append(i**2)
sqrDict[m] = numbers
i += 1
print('sqrDict =', sqrDict)

我希望我的字典是:

sqrDict = {'jan': [1], 'feb': [1, 4], 'mar': [1, 4, 9], 'apr': [1, 4, 9, 16]}

但是我现在拥有的是:

sqrDict = {'jan': [1, 4, 9, 16], 'feb': [1, 4, 9, 16], 'mar': [1, 4, 9, 16], 'apr': [1, 4, 9, 16]}
我不明白是什么问题。我的代码出了什么问题?

问题是您正在设置sqrDict[m] = numbers。最后,字典中的所有值都指向numbers。这将修复您的代码,因为它将sqrDict中的每个位置分配给,而不是指向它,这是通过改变numbers[] to numbers[:]来实现的,如下所示:

months = ['jan', 'feb', 'mar', 'apr'] #this is the list of keys of the Dictionary
numbers = []
sqrDict = {}
i = 1
for m in months:
numbers.append(i**2)
sqrDict[m] = numbers[:]
i += 1
print('sqrDict = ',sqrDict)

最新更新