How to create a loop to write json files with two arguments from difrent lists in python

Question:

I would like to modify my code with a for loop for:

  • first to create a list of files to create fnames = []
  • secondly to create a list of json_dics = []

I currently have a separate variable for each file

file_xx = f'{root_path}/{output}/{file_name_xx}.{json_ext}'

and separate variable for each json_dics

json_dic_xx = [{"test": "test", "test1" : "test1"}]

I use functions to write data to files

def save_to_json(json_dic, data_to_save):
    with open(data_to_save, 'w', encoding= utf_8) as json_file:
        json.dump(json_dic, json_file, ensure_ascii= False, indent=4, sort_keys= True)

save_to_json(json_dic_xx, file_xx)

I would like to create a for loop that, using the save_to_json() function, would take two arguments, one from the fnames = [], the other from the json_dics = [], and write the data to the appropriate files accordingly.

EDIT: my solution after making corrections by Rubén Pérez

output_file_names = ['filename01', `filename02', 'filename03']

fnames = []
for fname in output_file_names:
    fnames.append(f'{root_path}/{output}/{fname}.{json_ext}')

json_dics = [[] for _ in range(len(fnames))]


for i in range(len(fnames)):
    save_to_json(json_dics[i], fnames[i])
Asked By: Kubix

||

Answers:

for i in range(xx):
    save_to_json(json_dics[i], fnames[i])

EDIT: You can also create a loop for the first lines:

Assume you have every file_name_xx in a list filenames = [].

fnames = []
for filename in filenames:
     fnames.append(f'{root_path}/{output}/{filename}.{json_ext}')

You can do the same with json_dic

Answered By: Rubén Pérez

You can use zip() function to iterate over both the json_dics list as it will help with that. Below is an example:

json_dics = [json_dic_01, json_dic_02, json_dic_03, json_dic_04, json_dic_05, json_dic_06, json_dic_07]
fnames = [file_01, file_02, file_03, file_04, file_05, file_06, file_07]

for json_dic, fname in zip(json_dics, fnames):
    save_to_json(json_dic, fname)
Answered By: Abdulmajeed
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.