Home > OS >  writing a dict (of list) to a file.txt
writing a dict (of list) to a file.txt

Time:11-10

I get stuck with writing a dict of list to a .txt file.

I have a dict of lict like this:

product_menu_list = {"Shirt": ["Red", "Orange", "Purple"], "Dress": ["Blue", "Yellow", "Green"]}

To write it into a .txt file, I wrote:

product_lines = product_menu_list
with open('product_record.txt', 'w') as f:
    for line in product_lines:
        f.write(json.dumps(product_lines))
        f.write('\n')

By writing the above code, I can just get:

{"Shirt": ["Red", "Orange", "Purple"], "Dress": ["Blue", "Yellow", "Green"]}

That's not the format I want.

However, what I want is to write it line by line in the .txt file, like:

Shirt:
    Red
    Orange
    Purple

Dress:
    Blue
    Yellow
    Green

How can I achieve the expected output?

CodePudding user response:

IIUC,

product_lines = product_menu_list
with open('product_record.txt', 'w') as f:
    for key, value in product_lines.items():
        f.write(f'{key}\n')
        for v in value: 
            f.write(f'    {v}\n')
        f.write('\n')

You will get:

Shirt:
    Red
    Orange
    Purple

Dress:
    Blue
    Yellow
    Green

CodePudding user response:

Something like this should work, I recommend taking a look at the comments to learn from this, instead of just copying the code. It might help you in the future with similar problems.

# file should be the file opened (using open(...))
# data is the dictionary you want to write
def write_dict(file, data : dict):
    # for each key in the dictionary
    for k, v in data.items():
        # write key
        file.write(str(k)   ":\n")
        # write list of values
        if type(v) == list:
            for item in v:
                # \t is the tab at the front, \n is the newline
                file.write("\t"   str(item)   "\n")
        # write one newline at the end
        file.write("\n")

# to use it:
with open('test.txt', 'w') as f:
    write_dict(f, {
        "Key1" : [ "A", "B", "C" ],
        "Key2" : [ "D", "E", "F" ]
    })
  • Related