checking if a list in a text file already exists and appending to it
问题 So from this: Lucy:4 Henry:8 Henry:9 Lucy:9 To this Lucy: 4,9 Henry: 8,9 this is now fixed thank you 回答1: Very straight forward solution might be like this: (If you don't want to use defaultdict) with open('input.txt') as f: dic = {} for line in f: key,value = line.strip().split(':') dic.setdefault(key,[]).append(value) with open('output','a') as f: for key,value in dic.items(): f.write(key + ':' + ','.join(value) + '\n') UPDATE I have fixed your code, and you need to change this lines: