简体   繁体   中英

Pack dictionary with values separated by comma

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM