Gage
Gage

Reputation: 19

How to convert a list to a dictionary AND add random value for the key

I'm sure I worded the question weird but bear with me...

Here is a sample of code I wrote

players = []
choices = ["Rock", "Paper", "Scissors"]

for i in range(1, number_of_players + 1):
  players.append("P" + str(i))
  players_dictionary = dict.fromkeys(players, random.choice(choices))

If the number of players is, for example, 5, it will output

{ 'P1': 'Rock', 'P2': 'Rock', 'P3': 'Rock', 'P4': 'Rock', 'P5': 'Rock' }

I don't want each key to be the same, I want them to be randomized from the choices list. How can I implement that?

Upvotes: 0

Views: 463

Answers (1)

j1-lee
j1-lee

Reputation: 13939

How about the following, using dict comprehension?

import random

choices = ["Rock", "Paper", "Scissors"]

d = {f'P{p+1}': random.choice(choices) for p in range(5)}
print(d) # {'P1': 'Paper', 'P2': 'Rock', 'P3': 'Scissors', 'P4': 'Paper', 'P5': 'Scissors'}

In your code, dict.fromkeys is the culprit. The python doc about fromkeys says:

All of the values refer to just a single instance, so it generally doesn’t make sense for value to be a mutable object such as an empty list. To get distinct values, use a dict comprehension instead.

Upvotes: 3

Related Questions