我有以下文本文件datafile.txt
Pin AccountNumber FirstName LastName AccountBalance AccountType
2221 436115 Bob Smith 100.00 Checking
我需要加载文本文件并将其加载到字典中,并将pin作为键。这是我到目前为止,我不明白如何继续
bData = open('datafile.txt')
for line in bData:
bInfo = line.split()
print(bData)
答案 0 :(得分:2)
首先,跳过标题行
next(bData)
然后使用dict理解和星形解包(python 3)在一行中构建dict:
d = {k:v for k,*v in (line.split() for line in bData)}
符合python 2:
d = {s[0]:s[1:] for s in (line.split() for line in f)}
结果:
{'2221': ['436115', 'Bob', 'Smith', '100.00', 'Checking']}
(当然,您需要添加更多行才能获得更多键)