pythondictionary

How do I make a list in dictionary


This is my simple code for noting down dreams from Python crash course practices 10.7

In this practice I tried to make a list of dreams instead of simply adding a value to key but don't how to make a list. I did use list() but didn't work out well.

How can I fix this?

 dream_makers = {}

active = True
active2 = True

message = "hello\n\t here we save all your dreams to remind you later or when you achive it :)"
message += "whats your name\nenter 'quit' to exit\t"

while active :
    name = input(message)
    if name == "quit" :
        break
    
    dream = input("what are your dreams")
    dream_makers[name] = dream
    while active2:
        sdream = input("do you have another dream to achive? \nIF NOT ENTER NO")
    
        if sdream != "NO":
            dream_makers[name] = dream.append(sdream)
            continue
        else :
            active2 = False

Solution

  • tldr Just change the second line here:

    dream = input("what are your dreams")
    dream_makers[name] = dream
    

    to

    dream = input("what are your dreams")
    dream_makers[name] = [dream]
    

    Then the first dream will be the sole element of a list, with a single element, and your following append:

            dream_makers[name] = dream.append(sdream)
    

    will be on the right track - but it is attached to the wrong place: "dream" is just the return of the input on the previous line: a plain string. WHat is now a list is the content of dream_makers[name] - and, since it is a list, it features an .append method. So you can change it like this:

    ...
    while active2:
        sdream = input("do you have another dream to achive? \nIF NOT ENTER NO")
    
        if sdream != "NO":
            dream_makers[name].append(sdream)
            continue
    
        ...
    

    Happy studying -- only practicing a lot like this will get you a grasp of what is going on, so you are on the right track.