[Python] Best way to add dictionary entry and append to JSON file in Python

Discussão em 'Python' iniciado por Stack, Abril 22, 2025.

  1. Stack

    Stack Membro Participativo

    I have a need to add entries to a dictionary with the following keys:

    name
    element
    type


    I want each entry to append to a JSON file, where I will access them for another piece of the project.

    What I have below technically works, but there are couple things(at least) wrong with this.

    First, it doesn't prevent duplicates being entered. For example I can have 'xyz', '4444' and 'test2' appear as JSON entries multiple times. Is there a way to correct this?

    Is there a cleaner way to write the actual data entry piece so when I am entering these values into the dictionary it's not directly there in the parentheses?

    Finally, is there a better place to put the JSON piece? Should it be inside the function?

    Just trying to clean this up a bit. Thanks

    import json

    element_dict = {}


    def add_entry(name, element, type):

    element_dict["name"] = name
    element_dict["element"] = element
    element_dict["type"] = type
    return element_dict


    #add entry
    entry = add_entry('xyz', '4444', 'test2')


    #export to JSON
    with open('elements.json', 'a', encoding="utf-8") as file:
    x = json.dumps(element_dict, indent=4)
    file.write(x + '\n')

    Continue reading...

Compartilhe esta Página