0

Hey guys I'm trying to combine these two lists into one dictionary. However, on the second for loop it just keeps going through that and not going back to the first. Any help would be really appreciated. Thank you!

import random chores = ['dishes','bathroom','vacuum','walk dog'] assign = {} emails = ['a','b','c','d'] x=0 while x < 4: for i in chores: randomChore = random.choice(chores) chores.remove(randomChore) for key in emails: assign[key] = randomChore x = x + 1 

3 Answers 3

1

You only need random.shuffle, and it works like this

import random chores = ['dishes','bathroom','vacuum','walk dog'] assign = {} emails = ['a','b','c','d'] random.shuffle(chores) res = {key:val for key,val in zip(emails,chores)} 
Sign up to request clarification or add additional context in comments.

Comments

0

in your code, the for key in emails: part needed to be removed. it would choose the random chore then loop through, adding the emails without choosing another random chore.

here is the working code.

import random chores = ['dishes','bathroom','vacuum','walk dog'] assign = {} emails = ['a','b','c','d'] x = 0 for i in range(0, len(chores)): randomChore = random.choice(chores) chores.remove(randomChore) assign[emails[x]] = randomChore x = x + 1 print(assign) 

6 Comments

This one works too (+1) not sure who downvoted, but you can make a little compact
I suggest you try this with only three items in each list. And also explain why you need the outside while loop?
good idea to simplify the code, I was trying to point out where they got it wrong. I will edit it
What you are doing wrong is deleting items from the list you are iterating over. That's never a good idea.
Thank you!! This was so simple and I was stuck on it for so long.
|
0

Here, you don't need the useless inner and while loop an iterate over keys instead:

import random chores = ['dishes','bathroom','vacuum','walk dog'] assign = {} emails = ['a','b','c','d'] for i in emails: randomChore = random.choice(chores) chores.remove(randomChore) assign[i] = randomChore print(assign) 

4 Comments

Why the downvote on this answer? This works properly.
ikr mine got downvote too.... confusion. ill upvote, it works
Don't know if this is worth a downvote, but it's pretty bad that you needed to destroy the input chores in order to do this. Also removing items in an array in a loop is inefficient — you have essentially made a simple thing require O(n²) complexity. It makes a lot more sense to just shuffle the array.
So if I understand correctly, if you have two for loops it will keep iterating over the second one and then go back to the first?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.