sgerbhctim
sgerbhctim

Reputation: 3640

Writing a dictionary to txt file, any way to format it?

I wrote a little function to take dictionaries in Python and convert them to a txt file.

def dict_to_txt(dict, name):
    dict = {'dict': dict}

    with open('{}.txt'.format(name), 'w') as file:
        file.write(json.dumps(dict))

My output looks like the following:

{"dict": {"A": "America", "B": NaN, "C": "?", "D": NaN}}

Is there any way that I can output a formatted dictionary like this:

{"dict": {"A": "America", 
          "B": NaN, 
          "C": "?", 
          "D": NaN 
 }
}

or some variation of this. To give you some context, I have a list containing dictionaries and am applying this function via iterating through the list..

Upvotes: 1

Views: 1346

Answers (1)

sgerbhctim
sgerbhctim

Reputation: 3640

def dict_to_txt(dict, name):
    dict = {'dict': dict}

    with open('{}.txt'.format(name), 'w') as file:
        file.write(json.dumps(dict, indent=2))

Upvotes: 3

Related Questions