繁体   English   中英

如何读取文件并将它们存储在字典中。 不使用 zip

[英]How to read a file and store them in dictionary. without using zip

我需要读取包含第一行作为键和第二行作为值的文件。 我能够打开文件并阅读它,但我无法将其分配给字典格式。

def ticker(n):
infile = open(n)
content = infile.readlines()
c = {}
for lines in content:
    print (lines)

下面是我的输出,但我无法将第一行分配给键,将第二行分配给值。

WHOLE FOODS MARKET
WFMI
WYNN RESORTS, LTD
WYNN
XILINX
XLNX
XM SATELLITE RADIO HOLDINGS
XMSR
YAHOO
YHO

谢谢。

使用字典生成器:

{content[i]:content[i+1] for i in range(0, len(content)-1, 2)}

在您的代码中,如下所示:

def ticker(n):
    infile = open(n)
    content = infile.readlines()
    infile.close()  # Remember to close your file objects... (or use with block)
    return {content[i].strip():content[i+1].strip() for i in range(0, len(content)-1, 2)}

或者,正如@ShadowRanger 建议使用 zip 和 slices:

def ticker(n):
    with open(n) as infile:
        content = infile.readlines()
        return dict(zip(content[::2], content[1::2]))

您将使用zip ,但不使用tee ,因为这会将所有行与下一行配对,而不会将偶数行与奇数配对。 要偶数与奇数配对,请执行以下操作:

def ticker(file_name):
   with open(file_name) as f:
      stripped = iter(map(str.rstrip, f))
      return dict(zip(*([stripped] * 2)))

这只是一个包裹dict各地的内联版本构造grouper itertools配方,虽然使用zip ,因为我们知道它的配对。

暂无
暂无

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

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