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
CodePudding user response:
Try using:
fileNames = []
for files in response.json()["files"]:
fileNames.append(files["fileName"])
I think you wrote "filename"
instead of "fileName"
("Name" capitalised).
CodePudding user response:
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.
CodePudding user response:
I was getting the KeyError, I just changed the key value to fileName instead of filename and it solved the problem.
CodePudding user response:
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"