Formatting python defaultdict results and converting into string

Viewed 47

The snippet works already however, I had been trying to format the result according to my needs but cannot figure out how.

from collections import defaultdict
data=defaultdict(int)
with open('data.txt') as f:
    for line in f:
        group, score, team = line.split(maxsplit=2)
        data[(group.strip(),team.replace('\n','').strip())]+=int(score)
sorteddata = sorted([[k[0],v,k[1]] for k,v in data.items()], key=lambda x:x[1], reverse=True)
print ('\n'.join(map(str, sorteddata)))

Sample File (data.txt):

alpha 1 dream team
bravo 3 never mind us
charlie 1 diehard
delta 2 just cool
echo 5 dont do it
falcon 3 your team
lima 6 allofme
charlie 10 diehard
romeo 12 justnow
echo 8 dont do it
    

Current Output:

['echo', 13, 'dont do it']
['romeo', 12, 'justnow']
['charlie', 11, 'diehard']
['lima', 6, 'allofme']
['bravo', 3, 'never mind us']
['falcon', 3, 'your team']
['delta', 2, 'just cool']
['alpha', 1, 'dream team']    

Wanted Output:

echo 13 dont do it
romeo 12 justnow
charlie 11 diehard
lima 6 allofme
bravo 3 never mind us
falcon 3 your team
delta 2 just cool
alpha 1 dream team   
1 Answers

Try to change the last print to:

print(*[" ".join(map(str, v)) for v in sorteddata], sep="\n")

This prints:

echo 13 dont do it
romeo 12 justnow
charlie 11 diehard
lima 6 allofme
bravo 3 never mind us
falcon 3 your team
delta 2 just cool
alpha 1 dream team

Or:

for subl in sorteddata:
    print(" ".join(map(str, subl)))
Related