Skip to main content
 首页 » 编程设计

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

2025年05月04日13Terrylee

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

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 和切片:

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