如何读取文件并将其存储在字典中。不使用拉链

时间:2015-11-11 18:30:22

标签: python dictionary

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

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

感谢。

2 个答案:

答案 0 :(得分:1)

使用dict生成器:

May

在您的代码中如下:

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

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

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)}

答案 1 :(得分:0)

您使用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 recipe的内联版本中,但使用zip,因为我们知道它是配对的。