Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

"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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading