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
CodePudding user response:
You can use a dict comprehension here 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.
CodePudding user response:
using get will not throw error if Questions or Answers does not exist, you can pass second parameter in get to return that value in case of any question or answer key does not exist
final = {each_item.get('Questions'): each_item.get('Answers') for each_item in my_list}
CodePudding user response:
A bit roundabout way of getting there, but in Python 3.8 you could also use the walrus := syntax combined with a straightforward dict comprehension:
data = [
{
"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
}
]
result = {(v := list(d.values()))[1]: v[v[0] 2].split('.', 1)[-1]
for d in data}
print(result)
Out:
{'Who is known as ‘Father of computers’?': 'Charles Babbage', 'Which among the following has low speed storage?': 'Magnetic disks'}
