I have a list of dictionaries. Occasionally, I want to change and save one of these dictionaries so that the new message is utilized if the script is restarted. Right now, I make that change by modifying the script and rerunning it. I'd like to pull this out of the script and put the list of dictionaries into a configuration file of some kind.
I've found answers on how to write a list to a file, but this assumes that it is a flat list. How can I do it with a list of dictionaries?
My list looks like this:
logic_steps = [ { 'pattern': "asdfghjkl", 'message': "This is not possible" }, { 'pattern': "anotherpatterntomatch", 'message': "The parameter provided application is invalid" }, { 'pattern': "athirdpatterntomatch", 'message': "Expected value for debugging" }, ]
To write a dictionary of list to CSV files, the necessary functions are csv. writer(), csv. writerows(). This method writes all elements in rows (an iterable of row objects as described above) to the writer's file object.
How to make python save a dictionary to a file. These are small programs that allows you to create a dictionary and then, when running the program, it will create a file that contains the data in the original dictionary. We can save it to one of these formats: Comma seperated value file (.
provided that the object only contains objects that JSON can handle (lists
, tuples
, strings
, dicts
, numbers
, None
, True
and False
), you can dump it as json.dump:
import json with open('outputfile', 'w') as fout: json.dump(your_list_of_dict, fout)
if you want each dictionary in one line:
import json output_file = open(dest_file, 'w', encoding='utf-8') for dic in dic_list: json.dump(dic, output_file) output_file.write("\n")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With