Search code examples
pythonfiledictionarytextprinting

Output from populating a dictionary differs from print statements within code block


Here are the contents of the text file that I wish to create a dictionary from. I want the keys to be the questions and a list of the question options as the associated values.

 1. Which of these best describes your physical frame?
 Small
 Medium
 Large
 
2. Which best describes your skin?
 Oily and soft with freckles or pimples
 Thick, oily, cool skin
 Dry
 
3. Which best describes your hair?
 Straight and fine
 Thick and lustrous
 Dry and curly
 
4. Which best describes your eyes?
 Large, pretty
 Small and dry
 Medium-sized; intense gaze
 
5. Which best describes how you talk?
 Fast and/or a lot!
 My words are sharp and concise.
 My speech is slow and calm.
 
6. What type of weather is your favorite?
 Warm
 Cool
 Cool and dry
 
7. How is your memory?
 I learn quickly, but I also forget quickly.
 I have a great memory!
 It takes me a while to commit something to memory, but once I do I don’t forget it.
 
8. Which best describes your personality?
 Responsible, nurturing, and sensitive
 Creative, joyful, and introspective
 Competitive, perceptive, and efficient
 
9. Which of these traits do you most identify with?
 I can be pretty stubborn.
 I get jealous easily.
 I’m often indecisive.
 
10. How about these traits? Which sounds the most like you?
 I’m very intuitive.
 I’m quite brave.
 I’m a loyal, faithful friend.
 
11. And these? Which sounds the most like you?
 I’m often restless.
 I can be irritable and impatient.
 I’m a loyal, faithful friend.
The following questions relate to how you act/feel when you’re under stress.
When you’re under stress do you tend to…

12. Experience insomnia?
 Yes
 No
 
13. Feel complacent?
 Yes
 No
 
14. Develop rashes or hives?
 Yes
 No
 
15. Lose weight?
 Yes
 No
 
16. Experience constipation or excess gas?
 Yes
 No
 
17. Overeat or lose your appetite?
 Yes
 No
 
18. Drink alcohol to excess?
 Yes
 No
 
19. Feel lazy or inert?
 Yes
 No
 
20. Easily lose your temper?
 Yes
 No
 
21. Retain water?
 Yes
 No
 
22. Seek change?
 Yes
 No
 
23. Sweat a lot or have excess body odor?
 Yes
 No
 
24. Feel anxious or fearful?
 Yes
 No
 
25. Eat hot, spicy foods?
 Yes
 No
 
26. Experience gastritis or ulcers?
 Yes
 No
 
27. Feel restless?
 Yes
 No
 
28. Sleep a lot?
 Yes
 No
 
29. Put on weight?
 Yes
 No

Here is the Code:

quiz = open("quiz.txt", "r")
quest_answer_dic = {}
answers = []
last_quest_lst =[] 
question = ""
for line in quiz:
    line = line.strip()

    if len(line.split()) > 0:

        if line[0].isdigit():

            if len(last_quest_lst)==0:
                question = line
                last_quest_lst.append(line)
            else:
                last_question = last_quest_lst.pop()
                print(last_question, end =" : ")
                print(answers)
                quest_answer_dic[last_question] = answers
                answers.clear()
                question = line
                last_quest_lst.append(question)

        else:
            answers.append(line)
            
print(quest_answer_dic)
quiz.close()

The print statement:

print(last_question, end =" : ")
print(answers)

Gives me the output that I expect my dictionary to be:

1. Which of these best describes your physical frame? : ['Small', 'Medium', 'Large']
2. Which best describes your skin? : ['Oily and soft with freckles or pimples', 'Thick, oily, cool skin', 'Dry']
3. Which best describes your hair? : ['Straight and fine', 'Thick and lustrous', 'Dry and curly']
4. Which best describes your eyes? : ['Large, pretty', 'Small and dry', 'Medium-sized; intense gaze']
5. Which best describes how you talk? : ['Fast and/or a lot!', 'My words are sharp and concise.', 'My speech is slow and calm.']
6. What type of weather is your favorite? : ['Warm', 'Cool', 'Cool and dry']
7. How is your memory? : ['I learn quickly, but I also forget quickly.', 'I have a great memory!', 'It takes me a while to commit something to memory, but once I do I don’t forget it.']
8. Which best describes your personality? : ['Responsible, nurturing, and sensitive', 'Creative, joyful, and introspective', 'Competitive, perceptive, and efficient']
9. Which of these traits do you most identify with? : ['I can be pretty stubborn.', 'I get jealous easily.', 'I’m often indecisive.']
10. How about these traits? Which sounds the most like you? : ['I’m very intuitive.', 'I’m quite brave.', 'I’m a loyal, faithful friend.']
11. And these? Which sounds the most like you? : ['I’m often restless.', 'I can be irritable and impatient.', 'I’m a loyal, faithful friend.', 'The following questions relate to how you act/feel when you’re under stress.', 'When you’re under stress do you tend to…']
12. Experience insomnia? : ['Yes', 'No']
13. Feel complacent? : ['Yes', 'No']
14. Develop rashes or hives? : ['Yes', 'No']
15. Lose weight? : ['Yes', 'No']
16. Experience constipation or excess gas? : ['Yes', 'No']
17. Overeat or lose your appetite? : ['Yes', 'No']
18. Drink alcohol to excess? : ['Yes', 'No']
19. Feel lazy or inert? : ['Yes', 'No']
20. Easily lose your temper? : ['Yes', 'No']
21. Retain water? : ['Yes', 'No']
22. Seek change? : ['Yes', 'No']
23. Sweat a lot or have excess body odor? : ['Yes', 'No']
24. Feel anxious or fearful? : ['Yes', 'No']
25. Eat hot, spicy foods? : ['Yes', 'No']
26. Experience gastritis or ulcers? : ['Yes', 'No']
27. Feel restless? : ['Yes', 'No']
28. Sleep a lot? : ['Yes', 'No']

However, when I print the contents of my dic I get:

'1. Which of these best describes your physical frame?': ['Yes', 'No'], '2. Which best describes your skin?': ['Yes', 'No'], '3. Which best describes your hair?': ['Yes', 'No'], '4. Which best describes your eyes?': ['Yes', 'No'], '5. Which best describes how you talk?': ['Yes', 'No'], '6. What type of weather is your favorite?': ['Yes', 'No'], '7. How is your memory?': ['Yes', 'No'], '8. Which best describes your personality?': ['Yes', 'No'], '9. Which of these traits do you most identify with?': ['Yes', 'No'], '10. How about these traits? Which sounds the most like you?': ['Yes', 'No'], '11. And these? Which sounds the most like you?': ['Yes', 'No'], '12. Experience insomnia?': ['Yes', 'No'], '13. Feel complacent?': ['Yes', 'No'], '14. Develop rashes or hives?': ['Yes', 'No'], '15. Lose weight?': ['Yes', 'No'], '16. Experience constipation or excess gas?': ['Yes', 'No'], '17. Overeat or lose your appetite?': ['Yes', 'No'], '18. Drink alcohol to excess?': ['Yes', 'No'], '19. Feel lazy or inert?': ['Yes', 'No'], '20. Easily lose your temper?': ['Yes', 'No'], '21. Retain water?': ['Yes', 'No'], '22. Seek change?': ['Yes', 'No'], '23. Sweat a lot or have excess body odor?': ['Yes', 'No'], '24. Feel anxious or fearful?': ['Yes', 'No'], '25. Eat hot, spicy foods?': ['Yes', 'No'], '26. Experience gastritis or ulcers?': ['Yes', 'No'], '27. Feel restless?': ['Yes', 'No'], '28. Sleep a lot?': ['Yes', 'No']}

Solution

  • You can achieve the result using defaultdict

    From what I gather, you look at the first character in the sentence. If the character is a digit, then the line is a key, value otherwise.

    For each value line, you need to append to the dictionary.

    from collections import defaultdict
    
    with open('text.txt') as f:
        lns = f.readlines()
    
    dct = defaultdict(list)
    key = ""
    
    for ln in lns:
        ln = ln.strip("\n")
        if ln:
            if ln[0].isdigit():
                key = ln
            else:
                dct[key].append(ln)
    
    for val in dct.items():
        print(val)
    

    Result:

    ('1. Which of these best describes your physical frame?', ['Small', 'Medium', 'Large'])
    ('2. Which best describes your skin?', ['Oily and soft with freckles or pimples', 'Thick, oily, cool skin', 'Dry'])
    ('3. Which best describes your hair?', ['Straight and fine', 'Thick and lustrous', 'Dry and curly'])
    ('4. Which best describes your eyes?', ['Large, pretty', 'Small and dry', 'Medium-sized; intense gaze'])
    ('5. Which best describes how you talk?', ['Fast and/or a lot!', 'My words are sharp and concise.', 'My speech is slow and calm.'])
    ('6. What type of weather is your favorite?', ['Warm', 'Cool', 'Cool and dry'])
    ('7. How is your memory?', ['I learn quickly, but I also forget quickly.', 'I have a great memory!', 'It takes me a while to commit something to memory, but once I do I don’t forget it.'])
    ('8. Which best describes your personality?', ['Responsible, nurturing, and sensitive', 'Creative, joyful, and introspective', 'Competitive, perceptive, and efficient'])
    ('9. Which of these traits do you most identify with?', ['I can be pretty stubborn.', 'I get jealous easily.', 'I’m often indecisive.'])
    ('10. How about these traits? Which sounds the most like you?', ['I’m very intuitive.', 'I’m quite brave.', 'I’m a loyal, faithful friend.'])
    ('11. And these? Which sounds the most like you?', ['I’m often restless.', 'I can be irritable and impatient.', 'I’m a loyal, faithful friend.', 'The following questions relate to how you act/feel when you’re under stress.', 'When you’re under stress do you tend to…'])
    ('12. Experience insomnia?', ['Yes', 'No'])
    ('13. Feel complacent?', ['Yes', 'No'])
    ('14. Develop rashes or hives?', ['Yes', 'No'])
    ('15. Lose weight?', ['Yes', 'No'])
    ('16. Experience constipation or excess gas?', ['Yes', 'No'])
    ('17. Overeat or lose your appetite?', ['Yes', 'No'])
    ('18. Drink alcohol to excess?', ['Yes', 'No'])
    ('19. Feel lazy or inert?', ['Yes', 'No'])
    ('20. Easily lose your temper?', ['Yes', 'No'])
    ('21. Retain water?', ['Yes', 'No'])
    ('22. Seek change?', ['Yes', 'No'])
    ('23. Sweat a lot or have excess body odor?', ['Yes', 'No'])
    ('24. Feel anxious or fearful?', ['Yes', 'No'])
    ('25. Eat hot, spicy foods?', ['Yes', 'No'])
    ('26. Experience gastritis or ulcers?', ['Yes', 'No'])
    ('27. Feel restless?', ['Yes', 'No'])
    ('28. Sleep a lot?', ['Yes', 'No'])
    ('29. Put on weight?', ['Yes', 'No'])