Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to append a python dictionary to json file using python

I have a section named submissions and in the section users with multiple commands each with the command and the description like this:

{
    "submissions" : {
        "user1" : {
            "cmd1" : {
                "cmd" : "help",
                "des" : "Command to get help"
            }
        },
        "user2" : {
            "cmd1" : {
                "cmd" : "hello",
                "des" : "Greeting"
            }
        }
    }
}

Is there a way to append a new command to a user or a new user to the submissions like you can do with lists using Python?

For example you have this list:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    "list" : [
        {
            "name" : "Tom",
            "age" : 34
        }
    ]
}

and you can add new people to this list with:

...

person = {"name":"Kate","age":42}

data.append(person)

and kate appears on the list with the age.
But how can I define the new user so I can add this into the JSON file?

"user3" : {
            "cmd1" : {
                "cmd" : "New command",
                "des" : "New description"
            }
        }

When I try to add something like {"name":"Kate","age":34}(to show the error) to submissions with the .append(), it throws this error:

data["submissions"].append(user)
AttributeError: 'dict' object has no attribute 'append'

Can you add a new user to the JSON file with this formatting,
or is it better to store the user data like the list above?

>Solution :

If you have:

user3 = {
            "cmd1" : {
                "cmd" : "New command",
                "des" : "New description"
            }
        }

then you just need to put this dict under the key "user3":

data["submissions"]["user3"] = user3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading