Looping through dictionary and updating values

Question:

I would like to cycle through a list of questions and for each answer update the key-value pair in the corresponding position. So for the first iteration, it presents the first question in the list and updates the first key-value pair in a dictionary.

Right now the below code works but obviously only presents the first question and updates the first key-value pair, how can I get it to cycle through?

#question lists
general_questions = [
    "What is your biological sex? 1 for Male, 2 for Female: ",
    "What is your gender identity? 1 for Man, 2 for Woman, 3 for Non-binary, 4 for Genderfluid: ",
    "What is your age? ",
    "On a scale from 1 (Very conservative) through 4 (Centrist) to 7 (Very liberal), please indicate your political values: "
]

#user profile
general = {
    "sex": 0,
    "gender": 0,
    "age": 0,
    "values": 0
}

for x in general_questions:  # for all dictionaries in general_question...
    print(x)  # x is the dictionary in this iteration
    answer = input("nAnswer: ")
    for v in general:  # for all keys in x...
        general[v] = answer  # k is the key in this iteration
print(general)
Asked By: a_tasty_villain

||

Answers:

When you iterate over the general_questions list with for x in general_questions, x is the question. general_questions[0] will just always be the first question.

Associating the question with the correct entry in the general dictionary (the answers) is tricky because of the way you’ve chosen to set up this data. One solution might be to zip the two together:

for q, a in zip(general_questions, general):
    general[a] = input(f"{q}nAnswer: ")
print(general)

This only works because the ordering of the questions list and the keys in the answer dict is the same — it’s not necessarily obvious by glancing at the code that the two match up that way, and if you were to switch around the order, you’d associate the answers with the wrong questions!

The way I might suggest doing it would be to make the questions and answers both dictionaries, with the same keys:

#question lists
general_questions = {
    "sex": "What is your biological sex? 1 for Male, 2 for Female: ",
    "gender": "What is your gender identity? 1 for Man, 2 for Woman, 3 for Non-binary, 4 for Genderfluid: ",
    "age": "What is your age? ",
    "values": "On a scale from 1 (Very conservative) through 4 (Centrist) to 7 (Very liberal), please indicate your political values: "
}

#user profile
general_answers = {}

for k, q in general_questions.items():
    general_answers[k] = input(f"{q}nAnswer: ")

print(general_answers)
Answered By: Samwise
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.