-3

I have a dictionary with the following information

dict = {'key1':['1:2','2:3','3:4'], 'key2':['4:5','5:6']}

I need to out put this to a text file using the following format, the key and its values are to be commar seperated, with no '' quotation marks, each key and its values are to be separated by a new line

key1,1:2,2:3,3:4
key2,4:5,5:6

If i use the following code i do not get the intended output, any help would be appreciated

with open('test.txt', 'w', encoding = 'utf-8') as f:
     f.writelines(f'{k},{v}\n'for k,v in dict .items())
Pythonuser
  • 203
  • 1
  • 11

1 Answers1

0

Just use join as Patrick says:

d = {'key1':['1:2','2:3','3:4'], 'key2':['4:5','5:6']}

for k,v in d.items():
    print(f'{k},{",".join(v)}')

#or writing to a file:
with open('test.txt', 'w', encoding = 'utf-8') as f:
     f.writelines(f'{k},{",".join(v)}\n' for k,v in d.items())

Output as requested

quamrana
  • 37,849
  • 12
  • 53
  • 71