ILoveU3000
ILoveU3000

Reputation: 65

How do I create a new variable for a list everytime a new key is introduced?

I am trying to write a code which asks different users about their dream vacation destinations. It's a dictionary where the key is the poll taker's name and the value is a list called 'dream_vacations'. I want to create a new variable when a new key is created. What is the best way to do that?

vacation_poll = { }

dream_vacations = [ ]

while True:

    name = input('What is your name?: ')
    while True:
        dream_vacation = input('Where would you like to visit?: ')

        repeat = input('Is there anywhere else you like to visit? (Yes/No): ')
        dream_vacations.append(dream_vacation)

        if repeat.lower() == 'no':
            vacation_poll[name] = dream_vacations
            break

    new_user_prompt = input('Is there anyone else who would like to take the poll? (Yes/No): ')

    if new_user_prompt.lower() == 'no':
         break

My current code doesn't work because every key created will have the same values.

Upvotes: 1

Views: 42

Answers (2)

Nullman
Nullman

Reputation: 4279

try changing

vacation_poll = { }
dream_vacations = [ ]
while True:

into

vacation_poll = { }
while True:
    dream_vacations = [ ]

the reason they all have the same dream vacations, is because when you assign dream_vacations, you are referencing the same list. if you dream_vacations = [ ] at the beginning of a new person, dream_vacations will point at an entirley unrelated list, and so no strange duplications

Upvotes: 1

toastrackengima
toastrackengima

Reputation: 8762

You don't need to create a new variable (and I can think of no situation in which you would want to so dynamically). Instead, simply empty dream_vacations each time, i.e:

new_user_prompt = input('Is there anyone else who would like to take the poll? (Yes/No): ')

dream_vacations = []

if new_user_prompt.lower() == 'no':
     break

This sets it to a blank list, so it is now empty and works for the next user.

Upvotes: 1

Related Questions