Saving a list of dictionaries to file python 3

Viewed 1222

Hi I have to write a function that takes as arguments dictionaries and file name and saves it into a file with each dictionary in new line:
For example this is the list of dictionaries:

[[{'a': 1, 'b': 2}, {'aa': 2, 'bb': 3}]

This is my code:

def write_list_of_ngram_dicts(list_of_dicts, filename):
    import json
    open(filename, 'w', encoding='utf-8')
    for dic in list_of_dicts:
        json.dump(dic, filename)
        filename.write("\n")

But sadly it doesn't work and I don't understand why?, maybe there is another way to do it?
thank you:)

2 Answers

This will print each list in new line

def write_list_of_ngram_dicts(list_of_dicts, filename):
    with open(filename, 'w', encoding='utf-8') as file:
        for dic in list_of_dicts:
            data=json.dumps(dic) 
            file.write(data)
            file.write("\n")

This will print each dictionary in new line

def write_list_of_ngram_dicts(list_of_dicts, filename):
    with open(filename, 'w', encoding='utf-8') as file:
        for lists in list_of_dicts:
            for dic in lists:
                data=json.dumps(dic) 
                file.write(data)
                file.write("\n")

Does this solve your question?

WILL CREATE A FILE WITH NAME: check.txt

d = [[{'a': 1, 'b': 2}, {'aa': 2, 'bb': 3}], "check.txt"]

with open(d[1], "w") as f:
    for i in range(len(d[0])):
        f.write(str(d[0][i])+"\n")

RESULT:

{'a': 1, 'b': 2}
{'aa': 2, 'bb': 3}

Hope so that this information is useful to and answers you question!
Happy Coding!

Related