granttes
granttes

Reputation: 31

How to append values to a list in a dictionary while using a while loop?

vacation_poll = {}

name_prompt = "\nWhat is your name? "
vacation_spot_prompt = "\nWhere would you like to go on vacation? "
repeat_prompt = "\nWould you like to continue? (yes/no) "

active = True
while active:
    name = input(name_prompt)
    vacation_spot = input(vacation_spot_prompt)
    vacation_poll[name] = [vacation_spot]
    repeat = input(repeat_prompt)
    if repeat == 'no':
        active = False

for name, spots in vacation_poll.items():
    print("\nThese are " + name.title() + "'s places of interest: ")
    for spot in spots:
        print("\t" + spot.title())

print(vacation_poll)

My goal is to append a new vacation spot in a list inside the dictionary vacation_poll when the same key shows up. So if Joe shows up again after I continue the loop, the new vacation spot should be added to Joe's list of vacation spots, but instead I get it overwritten. I've tried to append using a for loop, but that didn't work either. How could I fix it to append a new value to the list each time the loop is continued?

Upvotes: 2

Views: 71

Answers (2)

jfahne
jfahne

Reputation: 231

You need to use a form of appending to the list. You cannot however just use one of the following:

vacation_poll[name]+=[vacation_spot]
vacation_poll[name].append(vacation_spot)

Doing this will throw an error because when a person's first vacation spot is being added, there is no value indexed at their name in the dictionary. Instead the get(index, default) method is needed.

vacation_poll[name]=vacation_poll.get(name, [])+[vacation_spot]

This will be have as desired. When the key is not yet in the dictionary, get() will return the second parameter, the default value, which is an empty list in this case.

Upvotes: 2

RagingRoosevelt
RagingRoosevelt

Reputation: 2164

Have you thought about the schema you'd like to use for the dictionary? From your code, it looks like you're trying to do something like

vacation_poll = {
    'Bob': ['Fiji', 'Florida', 'Japan'],
    'Joe': ['Disney Land', 'Six Flags', 'Lego Land']
}

When I approach these sorts of problems, usually what I do is set an if statement to check if the key doesn't yet exist in the dictionary and if it doesn't, I initialize it with a list:

if name not in vacation_poll:
    vacation_poll[name] = []

This lets me not worry about if the list didn't already exist later in my code and I could do something like

vacation_poll[name].append(vacation_spot)

because after I'd initialized the value associated with name to be a list, I can count on a list being there.

In your case, you might consider using a set instead of a list since it forces only unique values to be stored. This way, if the user enters the same value twice, it'll only record it once even after inserting it again the second time.

Upvotes: 2

Related Questions