Home > Software engineering >  list of dictionary comprehension in Python
list of dictionary comprehension in Python

Time:09-30

I have a class called Question. And I have a list of dictionary, I want to add those data into another list called questions_bank. I already do that using for loop and append method. But I want to do this using dictionary comprehension. Is there any way to do this ?

class Question:
    def __init__(self, text, answer):
        self.text = text
        self.answer = answer


data = [
    {
        "question": "question 1",
        "answer": True
    },
    {
        "question": "question 2",
        "answer": False
    }

]
question_bank = []

for value in data:
    question_bank.append(Question(value["text"], value["answer"]))

CodePudding user response:

The equivalent list comprehension to your for loop would be

>>> question_bank = [Question(i['question'], i['answer']) for i in data]
>>> question_bank
[<__main__.Question object at 0x0000020E4E62E9C8>, <__main__.Question object at 0x0000020E4E6B2888>]

CodePudding user response:

Even cleaner with dataclass

from dataclasses import dataclass

@dataclass
class Question:
        question: str
        answer :bool

data = [
    {
        "question": "question 1",
        "answer": True
    },
    {
        "question": "question 2",
        "answer": False
    }

]
question_bank = [Question(**q) for q in data]
print(question_bank)

output

[Question(question='question 1', answer=True), Question(question='question 2', answer=False)]
  • Related