Reputation: 349
I have a text file like this:
key1 value1 A
key1 value2 B
key1 value3 A
key2 value1 A
key2 value2 B
I am trying to open it as a dictionary and print the list of keys and values separated by commas so it looks like this in the end:
key1 value1,value2,value A,B,A
key2 value1,value2,value A,B
I am trying the following code:
f = open('file.txt', 'r')
answer = {}
for line in f:
list = ",".join(map(str,f))
print list
But it's not working
Any ideas what I am doing wrong? Thanks for your help
Upvotes: 0
Views: 249
Reputation: 174624
You are initializing a dictionary, but then you never use it in the loop. Try this approach instead:
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))
Also, don't use list
as the name of a variable.
Upvotes: 0
Reputation: 369064
Using collections.defaultdict
:
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)
output:
key1 value1,value2,value3 A,B,A
key2 value1,value2 A,B
Upvotes: 2