MdCAL12
MdCAL12

Reputation: 3

Combining two lists randomly

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

Upvotes: 0

Views: 77

Answers (3)

TheSavageTeddy
TheSavageTeddy

Reputation: 204

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)

Upvotes: 0

wasif
wasif

Reputation: 15470

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)

Upvotes: 0

meTchaikovsky
meTchaikovsky

Reputation: 7666

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)}

Upvotes: 1

Related Questions