How to append value of a JSON response in a list (python)?

Question:

i am getting response from request.post() as this:

{'total': 3,
 'files': [{'fileName': 'abc.mp4', 'size': '123'},
           {'fileName': 'def.mp4', 'size': '456'},
           {'fileName': 'ghi.mp4', 'size': '789'}]
}

i just want the filename value from this response and store it in an str list.

i have tried the following loop to do the same but it is showing some error:

        fileNames = []
        for files in response.json()["files"]:
            fileNames.append(files["filename"])

i expected the list of filenames but got some error

Asked By: Shivam Kumar

||

Answers:

Try using:

fileNames = []
for files in response.json()["files"]:
    fileNames.append(files["fileName"])

I think you wrote "filename" instead of "fileName" ("Name" capitalised).

Answered By: kaliiiiiiiii

the key is of a Dict is case sensitive, so you need to change the used key inside the loop with an upper case "N":

    fileNames = []
    for files in response.json()["files"]:
        fileNames.append(files["fileName"])

I tested this, and you will get just the file names in the "fileNames" list.

Answered By: Anrufliste

I was getting the KeyError, I just changed the key value to fileName instead of filename and it solved the problem.

Answered By: Shivam Kumar

You can do via list comprehension as well:

fileNames = [files["fileName"] for files in response.json()["files"]]

and as stated by others as well it should be "fileName" instead of "filename"

Answered By: God Is One
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.