读入文件和打印字典

时间:2017-06-14 21:42:25

标签: python dictionary file-io key

这是我的输入文件:

Drew, Matthew J., s1058828
Howerth, Chloe E., s1002240
Karolewicz, Michael J., s0995867
Perzely, Connor J., s0958005
Tanenbaum, Roberto, s1124377
Guan, Tiffany, s1103462
Jaligama, Vishnu Praneeth, s1143667
Jin, Ailan, s1152308

我是Python的新手,我的任务是获取名册文件并将其纳入词典和#34;现在"打印键:值。我觉得我很接近这个。

roster = {}
input_file = open("cs371598roster", "r")
whole_thing = input_file.read()
lines = whole_thing.split("\n")

for line in lines:
    last,first,ids = line.split(", ")

for i in range(len(last)):
    key = ids[i]
    val = first[i] + " " + last[i]
    roster[key] = val

print(roster)

2 个答案:

答案 0 :(得分:1)

你很亲密。但是,您不需要第二个循环。您可以在第一个名称中添加所有名称。

roster = {}
input_file = open("cs371598roster", "r")
whole_thing = input_file.read()
lines = whole_thing.split("\n")

for line in lines:
    last, first, ids = line.split(", ")
    roster[ids] = first + last

print(roster)

您之前的解决方案是将您的LAST行的名称和ID分解为单个字符并添加它们,可能不是您想要的。

答案 1 :(得分:0)

您应该使用with | as并将id设置为由空格连接的名字和姓氏的值。这有效:

roster = {}
input_file = open("cs371598roster", "r")
with input_file as f:
    for line in f:
        last, first, ids = line.split(", ")
        roster[ids.strip()] = ' '.join([first, last])

print(roster)