我的字典有问题。我正在使用 Python3。我确信有一些简单的东西我只是没有看到。
我正在从文件中读取行来创建字典。每行的前 3 个字符用作键(它们是唯一的)。从那里,我根据该行其余部分的信息创建一个列表。每 4 个字符组成列表的一个成员。创建列表后,我将列表作为值写入目录,该行的前三个字符作为键。
问题是,每次我向字典添加一个新的键值对时,它似乎会覆盖(或更新)先前写入的字典条目中的值。键很好,只是值发生了变化。因此,最后,所有键的值都等于文件中最后一行的列表。
我希望这是清楚的。任何想法将不胜感激。
下面是一段代码
formatDict = dict()
sectionList = list()
for usableLine in formatFileHandle:
lineLen = len(usableLine)
section = usableLine[:3]
x = 3
sectionList.clear()
while x < lineLen:
sectionList.append(usableLine[x:x+4])
x += 4
formatDict[section] = sectionList
for k, v in formatDict.items():
print ("for key= ", k, "value =", v)
formatFileHandle.close()
最佳答案
你总是清除,然后追加,然后插入相同的 sectionList
,这就是为什么它总是覆盖条目 - 因为你告诉程序它应该。
永远记住:在 Python 赋值中,从不创建一个副本!
简单修复
只需插入一个副本:
formatDict[section] = sectionList.copy() # changed here
而不是插入引用:
formatDict[section] = sectionList
复杂的修复
有很多事情正在发生,您可以通过对分组等子任务使用函数来使其“更好”,还应该使用 with
打开文件,这样文件会自动关闭,即使发生异常,应避免结束已知的 while
循环。
我个人会使用这样的代码:
def groups(seq, width):
"""Group a sequence (seq) into width-sized blocks. The last block may be shorter."""
length = len(seq)
for i in range(0, length, width): # range supports a step argument!
yield seq[i:i+width]
# Printing the dictionary could be useful in other places as well -> so
# I also created a function for this.
def print_dict_line_by_line(dct):
"""Print dictionary where each key-value pair is on one line."""
for key, value in dct.items():
print("for key =", key, "value =", value)
def mytask(filename):
formatDict = {}
with open(filename) as formatFileHandle:
# I don't "strip" each line (remove leading and trailing whitespaces/newlines)
# but if you need that you could also use:
# for usableLine in (line.strip() for line in formatFileHandle):
# instead.
for usableLine in formatFileHandle:
section = usableLine[:3]
sectionList = list(groups(usableLine[3:]))
formatDict[section] = sectionList
# upon exiting the "with" scope the file is closed automatically!
print_dict_line_by_line(formatDict)
if __name__ == '__main__':
mytask('insert your filename here')
关于Python3 字典值被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45919085/