user7468934
user7468934

Reputation:

Displaying certain items in lists

I am trying to create a set of questions with their respective topics and then I want to ask the user which questions they want to study. Depending on their response I then want to then display just those questions. (For example if they respond with "maths" I want all the questions with the topic "maths" to be displayed)

so far I have this code;

from collections import *

question = []
topic = []

t = 4

while t > 0:
    x = input("what is your question?")
    y = input("what is the topic?")
    question.append(x)
    topic.append(y)
    data = defaultdict(list)
    for topic, question in zip(topic, question):
        data[topic].append(question)

    t -= 1

z = input("what topic would you like to study?")
print(data[z])   

which works fine on the first iteration however when i enter the values in the second iteration this error occurs;

Traceback (most recent call last): File "C:/Users/Sam/PycharmProjects/ComputingProject/lists.py", line 11, in question.append(x) AttributeError: 'str' object has no attribute 'append'

why does it not work the second time around?

Upvotes: 1

Views: 60

Answers (1)

blue note
blue note

Reputation: 29071

zip creates pairs. In your case, you should probably use a dict, mapping from topic to a list of questions.

 data = defaultdict(list)
 for topic, question in zip(topics, questions):
     data[topic].append(question)

note: defaultdict is a variation of dict (which you should study first), to avoid checking if a topic already exists in the dict

Upvotes: 3

Related Questions