Bil*_*gan 2 python dictionary list python-3.x
我的字典有问题。我正在使用Python3。我敢肯定我只是看不到一些简单的东西。
我正在从文件中读取行以创建字典。每行的前3个字符用作键(它们是唯一的)。从那里,我根据该行其余部分的信息创建一个列表。每4个字符组成一个列表。创建列表后,我将目录作为值写入目录,并将行的前三个字符作为键。
问题是,每次我向字典中添加新的key:value对时,它似乎都会覆盖(或更新)先前编写的字典条目中的值。键很好,只是更改了值。因此,最后,所有键的值都等于文件最后一行的列表。
我希望这很清楚。任何想法将不胜感激。
下面的代码片段
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()
Run Code Online (Sandbox Code Playgroud)
您总是先清除,然后追加然后插入相同的内容sectionList,这就是为什么它总是会覆盖条目的原因-因为您告诉程序应该这样做。
永远记住:在Python作业中永远不会复制!
只需插入一个副本:
formatDict[section] = sectionList.copy() # changed here
Run Code Online (Sandbox Code Playgroud)
而不是插入引用:
formatDict[section] = sectionList
Run Code Online (Sandbox Code Playgroud)
发生了很多事情,您可以通过使用诸如分组之类的子任务功能使它“更好”,还应该使用文件打开文件,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')
Run Code Online (Sandbox Code Playgroud)