Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save a list of dictionaries to a file?

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"     }, ] 
like image 457
Python Novice Avatar asked Sep 11 '14 02:09

Python Novice


People also ask

How do I write a dictionary list in CSV?

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.

Can you save a Python dictionary to file?

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 (.


2 Answers

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) 
like image 122
mgilson Avatar answered Sep 21 '22 17:09

mgilson


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") 
like image 24
Reihan_amn Avatar answered Sep 19 '22 17:09

Reihan_amn