How to write a text file from a dictionary in Python with values going from a list to string?


I am trying to write a text file from a dictionary in which the dictionary values is a list that I want to convert to a string with "," separators, for example:

["string1","string2","string3"] --> "string1,string2,string3"

When the list becomes one string I want to write its key (also a string with : separator) with its corresponding string:


Is what should be written within the text file. The dictionary would look like this for example:

{'key1': ['string1', 'string2', 'string3'], 'key2': ['string4', 'string5', 'string6'], 'key3': ['string7', 'string8', 'string9']}

Here is the function I have so far but as shown not much is here:

def quit(dictionary):
    with open("file.txt", 'w') as f: 
        for key, value in dictionary.items(): 
            f.write('%s:%sn' % (key, value))

However it makes every item within the text file as a list so I am not sure how to fix it. I do not want to use built-ins (such as json), just simple for loops, and basic i/o commands.

Asked By: Cr3 D



You can use str.join to join the dictionary values with ,:

dct = {
    "key1": ["string1", "string2", "string3"],
    "key2": ["string4", "string5", "string6"],
    "key3": ["string7", "string8", "string9"],

with open("output.txt", "w") as f_out:
    for k, v in dct.items():
        print("{}:{}".format(k, ",".join(v)), file=f_out)

This creates file output.txt:

Answered By: Andrej Kesely
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.