def putinfotodict(infile):
outstr = {}
with open(infile) as inf:
for one in inf.read().split(',\n'):
stuid = one.split(',')[-1]
stuid = stuid[:-1]
claid = one.split(',')[-2]
atttime1 = one.split(',')[-3]
atttime = atttime1[1:]
valueandvalue = {}
valueandvalue['lessonid'] = claid
valueandvalue['checkintime'] = atttime
if stuid not in outstr:
outstr[stuid] = []
outstr[stuid].append(valueandvalue)
return outstr
infile = 'file2.txt'
p=putinfotodict(infile)
print(p)
import pprint
pprint.pprint(p)
'''
標準答案
def putinfotodict(filename):
redic={}
with open(filename) as f:
lines=f.read().splitlines()
for line in lines:
# remove '('and ')'
line=line.replace('(','').replace(')','').replace(';','').strip()
parts=line.split(',')
citime=parts[0].strip().replace("'",'')
lessonid=int(parts[1].strip())
userid=int(parts[2].strip())
toadd={'lessonid':lessonid,'checkintime':citime}
#if not in,need to create list first
if userid not in redic:
redic[userid]=[]
redic[userid].append(toadd)
#or just
## redic.setdefault(userid,[]).append(toadd)
return redic
infile = 'file2.txt'
p=putinfotodict(infile)
import pprint
pprint.pprint(p)
'''
网友评论