How to append a python dictionary to json file using python

Question:

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:

{
    "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?

Asked By: i_m_red

||

Answers:

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
Answered By: quamrana
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.