简体   繁体   English

Python 将文件转换为字典

[英]Python Converting File Into Dictionary

I am trying to read a.txt file that has the format我正在尝试读取具有以下格式的 a.txt 文件

"Field1:Field2:Field3:Field4"
"a:b:c:d"
"e:f:g:h"

into a dictionary with the format放入具有格式的字典

{Field1: [a, e], Field2: [b, f], Field3: [c, g], Field4: [d, h]}

and my current code looks like我当前的代码看起来像

with open("data.txt",'r') as filestream:
    lines = [line.strip().split(":") for line in filestream] 
    fields = lines[0] 
    d = dict.fromkeys(fields, []) 
    for i in range(1, len(lines)):
        for j in range(len(fields)):
            d[headers[j]].append(lines[i][j])

What I'm trying to do is convert each line in the file into a split and cleaned list, store that in a bigger list of lists, and then use a double for loop to match the key of the dictionary with the correct value in the smaller/current list.我想要做的是将文件中的每一行转换为一个拆分和清理的列表,将其存储在更大的列表列表中,然后使用双 for 循环将字典的键与较小/当前列表。 However, what the code ends up doing is adding to the dictionary in a way that looks like:但是,代码最终所做的是以如下方式添加到字典中:

{Field1: [a], Field2: [a], Field3: [a], Field4: [a]}
{Field1: [a,b], Field2: [a,b], Field3: [a,b], Field4: [a,b]}

I want to add to the dictionary in the following manner:我想通过以下方式添加到字典中:

{Field1: [a], Field2: [], Field3: [], Field4: []}
{Field1: [a], Field2: [b], Field3: [], Field4: []}

and so forth.等等。

Can anyone help me figure out where my code is going wrong?谁能帮我找出我的代码哪里出错了?

Try:尝试:

out = {}

with open("data.txt", "r") as f_in:
    i = (line.strip().split(":") for line in f_in)
    fields = next(i)
    for line in i:
        for k, v in zip(fields, line):
            out.setdefault(k, []).append(v)

print(out)

Prints:印刷:

{
    "Field1": ["a", "e"],
    "Field2": ["b", "f"],
    "Field3": ["c", "g"],
    "Field4": ["d", "h"],
}

The issue that you're having comes from the line:您遇到的问题来自以下行:

d = dict.fromkeys(fields, []) 

More specifically, the [] .更具体地说, [] What this line does here is that it creates a new dictionary with the fields as the keys, and the SAME empty list as the value for all the fields .此行在这里所做的是创建一个新字典,其中字段作为键,相同的空列表作为所有字段的值 Meaning that field1, field2, field3 and field4 are all using the same list to store their contents and this is the main reason as to why you're getting this problem.这意味着 field1、field2、field3 和 field4 都使用相同的列表来存储它们的内容,这是您遇到此问题的主要原因。

Your issue can be fixed through a single line change, from:您的问题可以通过单行更改来解决,来自:

d = dict.fromkeys(fields, []) 

to:到:

d = {field: [] for field in fields} 

Meaning that your source code would become:这意味着您的源代码将变为:

with open("data.txt",'r') as filestream:
    lines = [line.strip().split(":") for line in filestream] 
    fields = lines[0] 
    d = {field: [] for field in fields} 
    for i in range(1, len(lines)):
        for j in range(len(fields)):
            d[fields[j]].append(lines[i][j])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM