我试图读取一个看起来像这样的文件:
Lee
Louise
12345678
711-2880 Nulla St. Mississippi
Chapman
Eric
27681673
Ap 867-859 Sit Rd. New york
(...)
并将其作为字典,将last和firstname作为键,其值为lastname,firstname,tel和address。看起来应该是这样的:
{'Lee Louise': ['Lee','Louise','12345678','711-2880 Nulla St. Mississippi'],'Chapman Eric': ['Chapman','Eric','27681673','Ap #867-859 Sit Rd. New york']}
这就是我到目前为止所做的:
d = dict()
fr = open('file.txt', 'r').readlines()
info = [k.split('\n') for k in fr]
for k in range(len(info)):
if k % 4 == 0:
list = info[k :k + 4]
new_list = [b[0] for b in list]
d[info[k][0]] = new_list
return d
我只设法将姓氏设为密钥.. 如何将姓氏和名字都设为密钥?
答案 0 :(得分:2)
您的代码有几个问题
我会将代码片段重写为
info = open(...).read().splitlines() # Saves from re-building list
for offset in range(0, len(info), 4):
d[' '.join(info[offset: offset + 2]) = info[offset: offset + 4]
没有寄生列表 - 从 new_list 混乱
中保存答案 1 :(得分:0)
替换d[info[k][0]] = new_list
with:
d[" ".join([info[k][0],info[k][1]]]) = new_list