[英]How to read a file and store them in dictionary. without using zip
I need to read the file that contains first line as a key and the second line as a value.我需要读取包含第一行作为键和第二行作为值的文件。 I am able to open the file and read it but i am not able to assign it to the dictionary format.
我能够打开文件并阅读它,但我无法将其分配给字典格式。
def ticker(n):
infile = open(n)
content = infile.readlines()
c = {}
for lines in content:
print (lines)
Below is my output, but i am not able to assign the first line to key and second line to value.下面是我的输出,但我无法将第一行分配给键,将第二行分配给值。
WHOLE FOODS MARKET
WFMI
WYNN RESORTS, LTD
WYNN
XILINX
XLNX
XM SATELLITE RADIO HOLDINGS
XMSR
YAHOO
YHO
Thanks.谢谢。
Use a dict generator:使用字典生成器:
{content[i]:content[i+1] for i in range(0, len(content)-1, 2)}
In your code like so:在您的代码中,如下所示:
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)}
Or, as @ShadowRanger suggests using zip and slices:或者,正如@ShadowRanger 建议使用 zip 和 slices:
def ticker(n):
with open(n) as infile:
content = infile.readlines()
return dict(zip(content[::2], content[1::2]))
You'd use zip
, but not with tee
, since that would pair all lines with their next line, not even lines with odd.您将使用
zip
,但不使用tee
,因为这会将所有行与下一行配对,而不会将偶数行与奇数配对。 To pair even with odd, do:要偶数与奇数配对,请执行以下操作:
def ticker(file_name):
with open(file_name) as f:
stripped = iter(map(str.rstrip, f))
return dict(zip(*([stripped] * 2)))
This is just wrapping a dict
constructor around an inlined version of the grouper
itertools
recipe , though using zip
since we know it's paired up.这只是一个包裹
dict
各地的内联版本构造grouper
itertools
配方,虽然使用zip
,因为我们知道它的配对。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.