在CSV中追加带有多个字典的行

9w11ddsr  于 2023-03-15  发布在  其他
关注(0)|答案(1)|浏览(100)

我有一个正在写入CSV的调查。目前它从字典中获取键并将其分配为标题,然后从另一个字典中获取值并将其分配到下面的行。这一切都工作正常,但我还想在这些键和值行上附加一个额外的字典,以便它们水平延伸。
简而言之,我希望将来自另一个字典的键添加到标题行,并将来自相应字典的值添加到值行。
下面是完整代码:

import csv
from questions import general, sexual_preferences,
from answers import general_answers, sexual_preferences_answers

#define variable
should_continue = True

#create CSV and write header with question keys
with open('sexuality_raw_data.csv', 'w', newline='') as f:
    h = csv.DictWriter(f, general_answers.keys())
    h.writeheader()

#survey logic + sequence
while should_continue == True:
    general_answers["participants"] += 1
    print("\nPlease indicate your response according to the instructions given.\n")
    for k, q in general.items():
        general_answers[k] = input(f"\n{q}\nResponse: ")

    for k, q in sexual_preferences.items():
        sexual_preferences_answers[k] = input(f"\n{q}\nResponse: ")

    with open('sexuality_raw_data.csv', 'a', newline='') as f:
        r = csv.DictWriter(f, general_answers)
        r.writerow(general_answers)

    print("Would you like to restart the survey? Y/N")
    should_continue = input("Answer: ")
    if should_continue == "Y":
        should_continue = True
    else:
        should_continue = False
print(general_answers)
print(sexual_preferences_answers)

下面是general和general_answers字典的一个例子:

general = {
    "intro": "Assigning participant number."
             "\nAll data will be anonymised. Please indicate your consent using Y/N.",
    "sex": "What is your biological sex? "
            "\n1 for Male, 2 for Female.",
    "gender": "What is your gender identity?"
            "\n1 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.",
    "heterosexuality": "I prefer to sleep with people of the opposite gender."
            "\nOn a scale from 1 (Strongly disagree) through 4 (Neither agree nor disagree) to 7 (Strongly agree)",
    "pansexuality": "In terms of enjoying sex, gender is not important to me."
            "\nOn a scale from 1 (Strongly disagree) through 4 (Neither agree nor disagree) to 7 (Strongly agree)",
    "bisexuality": "I enjoy sleeping with people who identify as a man or a woman equally."
            "\nOn a scale from 1 (Strongly disagree) through 4 (Neither agree nor disagree) to 7 (Strongly agree)",
    "monogamous": "I prefer to only have one sexual partner at a time."
            "\nOn a scale from 1 (Strongly disagree) through 4 (Neither agree nor disagree) to 7 (Strongly agree)",
}

general_answers = {
    "participants": 0,
    "sex": 0,
    "gender": 0,
    "age": 0,
    "values": 0,
    "heterosexuality": 0,
    "pansexuality": 0,
    "bisexuality": 0,
    "monogamous": 0,
}

相关问题