[英]I'm trying to convert a text file to dictionary or a list Python
I have the following text file datafile.txt 我有以下文本文件datafile.txt
Pin AccountNumber FirstName LastName AccountBalance AccountType
2221 436115 Bob Smith 100.00 Checking
I need to load the text file and load it into a dictionary with the pin as the key. 我需要加载文本文件,并使用图钉作为键将其加载到字典中。 This is what I have so far and I do not understand how to proceed 这是我到目前为止的内容,我不知道该如何进行
bData = open('datafile.txt')
for line in bData:
bInfo = line.split()
print(bData)
first, skip the title line 首先,跳过标题行
next(bData)
then build the dict in one line using dict comprehension and star unpacking (python 3): 然后使用dict理解和星标拆解(python 3)在一行中构建dict:
d = {k:v for k,*v in (line.split() for line in bData)}
python 2 compliant: 兼容python 2:
d = {s[0]:s[1:] for s in (line.split() for line in f)}
result: 结果:
{'2221': ['436115', 'Bob', 'Smith', '100.00', 'Checking']}
(you need to put more lines to get more keys of course) (当然,您需要放置更多行才能获得更多键)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.