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

Time:11-25

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:

"key1:string1,string2,string3"
"key2:string4,string5,string6"
"key3:string7,string8,string9"

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:%s\n' % (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.

CodePudding user response:

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:

key1:string1,string2,string3
key2:string4,string5,string6
key3:string7,string8,string9
  • Related