0

Please help, I have a dictionary which I need to write to a txt file I need to change the formatting of the dic so that when I write to new file I can get the desired output below. Thanks!

my dict:

sdata = {'A': [1, 2, 3, 4], 'B': [128, 118], 'C': [5, 6, 7], 'D': [1, 3, 4]}

current output:

{'A': [1, 2, 3, 4], 'B': [128, 118], 'C': [5, 6, 7], 'D': [1, 3, 4]}

how can I save it to file in the format below instead of the one above?

Desired output:

 A, 1 2 3 4
 
 B, 128 118
 
 C, 5 6 7
 
 D, 1 3 4

following is my code:

def saveAndExit(sdata, x, r):
    outFileName = "updated.txt"
    outfile = open(outFileName, "w")
    print (f'Content of xxx after updated {x} was added to key{r}:')
    print (f'Content of xxx after updated {x} was added to key{r}:',file=outfile)
    print (sdata) # wrong format
    print (sdata, file=outfile)
    outfile.close()
Janice goh
  • 17
  • 6

3 Answers3

1

The following should do what you want:

for key, value in sdata.items():
    print(key + ", " + " ".join(str(v) for v in value))

This produces the following:

A, 1 2 3 4
B, 128 118
C, 5 6 7
D, 1 3 4

If you want to double-space the output, with blank lines between each line of data (as shown in the post), just add:

print()

to the loop.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
0

I would use unpacking operator (*) in print to get desired result, following way:

sdata = {'A': [1, 2, 3, 4], 'B': [128, 118], 'C': [5, 6, 7], 'D': [1, 3, 4]}
for key, value in sdata.items():
    print(f'{key},', *value, end='\n\n')

Output:

A, 1 2 3 4

B, 128 118

C, 5 6 7

D, 1 3 4

providing '\n\n' as end result to get blank lines.

Daweo
  • 31,313
  • 3
  • 12
  • 25
0

Try this:

print('\n\n'.join("%s, %s" % (k,str(sdata[k]).strip("[]").replace(",","")) for k in sdata.keys()))

The above will ensure the keys are stripped off brackets and commas. You can omit those if you want to.

Output:

A, 1 2 3 4

B, 128 118

C, 5 6 7

D, 1 3 4
Reva
  • 9
  • 2