简体   繁体   English

从转换列表到字典的迭代输出

[英]Output iterated from converting list to dictionary

this is an extract (full file has about 8k observations) of my input txt file, containing 3 elements (name, some identifier, year) separated by tab: 这是我输入的txt文件的摘录(完整的文件具有大约8k的观察值),包含3个元素(名称,某些标识符,年份),并用制表符分隔:

steve jobs      7653596   2007
john hancock    7653596   2007

I tried to put the list in a dictionary using: 我试图使用以下方法将列表放入字典中:

dictList = []
with open('filename.txt') as fo:
    for line in fo:
        elements = line.rstrip().split('\t')[0:]
        dictList.append(dict(zip(elements[0::3], elements[1::2])))
        print dictList

Output after executing the above: 执行以上命令后输出:

{'steve jobs': '7653596'}
{'steve jobs': '7653596', 'john hancock': '7653596'}

I'm not sure why the output gives me the result from the first item, and then the second item. 我不确定为什么输出会给我第一项和第二项的结果。 I just need the last line generated from the output. 我只需要从输出生成的最后一行。 Any idea how I should go about doing that? 知道我应该怎么做吗?

You are printing the dictionary on every iteration of the loop instead of after it. 您将在循环的每次迭代中而不是在循环之后打印字典。 Just indent it out, and you should be OK: 只需缩进即可,您应该可以:

dictList = []
with open('filename.txt') as fo:
    for line in fo:
        elements = line.rstrip().split('\t')[0:]
        dictList.append(dict(zip(elements[0::3], elements[1::2])))

    print dictList # Here

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

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