Convert specific json values as dictionary values in python
this is my example JSON file.
[
{
"Sl No.": 1,
"Questions": "Who is known as ‘Father of computers’?",
"Option A": "A.Vannevar Bush",
"Option B": "B.Charles Babbage",
"Option C": "C.Howard Aiken",
"Option D": "D.John Atansoff",
"Answers": "Charles Babbage",
"Level" : 2
},
{
"Sl No.": 2,
"Questions": "Which among the following has low speed storage?",
"Option A": "A.CD-ROM",
"Option B": "B.Extended storage",
"Option C": "C.Magnetic disks",
"Option D": "D.Magnetic tapes",
"Answers": "Magnetic tapes",
"Level" : 1
}
]
I'm trying to convert it into a python dictionary which should have question and answer pairs like this:
dic ={"Who is known as ‘Father of computers’?": "Charles Babbage","Which among the following has low speed storage?": "Magnetic tapes" }
And as of now I'm using this method to convert into dictionary:
json_file = open("import.json")
data = json.load(json_file)
questions = []
answers = []
for i in range(len(data)):
questions.append(data[i]["question"])
for i in range(len(data)):
answers.append(data[i]["answer"])
easy = dict(zip(questions, answers))
Here I'm iterating through the JSON file to find question and answer values and appending them to an empty list. Then I'm using the zip function to convert these 2 lists into dictionaries. I know this isn't a very optimized approach and as my application scales, I'll have to create multiple dictionaries for which I have to create 2 lists for every dictionary and then zip again. Is there any easier and better approach? Thank you
You can use a dictionary comprehension here. There, you iterate over an iterable and put key value pairs separate with a colon. That will generate a dictionary for you. In code, that reads like
result = {d["Questions"] : d["Answers"] for d in data}
Note that I habe used the keys as shown in the example not the ones used in your code.