我有一个这样的文本文件:
key1 value1 A
key1 value2 B
key1 value3 A
key2 value1 A
key2 value2 B
我正在尝试将其作为字典打开并打印由逗号分隔的键和值列表,因此它最终看起来像这样:
key1 value1,value2,value A,B,A
key2 value1,value2,value A,B
我正在尝试以下代码:
f = open('file.txt', 'r')
answer = {}
for line in f:
list = ",".join(map(str,f))
print list
但它不起作用
任何想法我做错了什么? 谢谢你的帮助
答案 0 :(得分:2)
from collections import defaultdict
with open('file.txt') as f:
answer = defaultdict(lambda: ([], []))
for line in f:
key, value, alpha = line.split()
answer[key][0].append(value)
answer[key][1].append(alpha)
for key, (values, alphas) in sorted(answer.items()):
print key, ','.join(values), ','.join(alphas)
输出:
key1 value1,value2,value3 A,B,A
key2 value1,value2 A,B
答案 1 :(得分:0)
您正在初始化字典,但之后您永远不会在循环中使用它。请尝试这种方法:
from collections import defaultdict
answers = defaultdict(list)
with open('file.txt') as inf:
for line in inf:
bits = line.rstrip().split()
answers[bits[0]].append(','.join(bits[1:]))
for key,values in answers.iteritems(): # in Python 3, use answers.items()
for value in values:
print('{} {}'.format(key, value))
另外,请勿使用list
作为变量的名称。