How would I add the results of a 'for' loop into a dictionary?

Question:

I am required to take 52 random outputs of cards. I got that in a for loop. The problem is, I need to save that output inside a variable.`

import random
r=random.randint(0, 9)

cards={'Spades':r, 'Clubs':r, 'Hearts':r, 'Diamonds':r,'Jack':10, 'King':10, 'queen':10,"Aces":1}
print(cards)

cards2={}

for i in range(52):
    global res
    res = key, val = random.choice(list(cards.items()))
    print("Your deck contains " + str(res))
    cards2.update(i) # All output should go in here

I tried using cards2.update, but it didn’t work.
I also tried using cards2.(keys).
I just need to create 52 random samples and store them as dictionary value pairs.

Asked By: Lop Pollo

||

Answers:

First remove the double assignment (res = key, val). And I don’t see any point in using a global variable here. Just do _dict[key] = value as shown below, and it will work fine. Also remember that you can’t get all 52 random cards, because if the key exists then the value will be replaced.

import random
r = random.randint(0, 9)

cards = {'Spades':r, 'Clubs':r, 'Hearts':r, 'Diamonds':r,'Jack':10, 'King':10, 'queen':10,"Aces":1}
print(cards)

cards2 = {}

for i in range(52):
    key, val = random.choice(list(cards.items()))
    cards2[key] = val

print(cards2)
Answered By: Anonymous
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.