Home > OS >  How to create random values for each key created in a dictionary
How to create random values for each key created in a dictionary

Time:10-28

I am trying to convert a list into a dictionary and assign the value from each key a random value, but I am seeming to have some trouble with it. Here is a sample of my code ...

def assign_players_value(player_list):
  choices = ["Rock", "Paper", "Scissors"]
  player_dictionary = dict.fromkeys(player_list, (random.choice(choices) for p in range(number_of_players)))
  print (player_dictionary)

Do keep in mind, the player_list looks like ["P1", "P2", "P3"...]

My intended output is something like {"P1" : "Rock", "P2" : "Scissors" , "P3" : "Paper" ... }

But instead, I get {'P1': <generator object assign_players_value.. at 0x000001B88B0FD350>, 'P2': <generator object assign_players_value.. at 0x000001B88B0FD350>, ...

CodePudding user response:

You can do something like this

def assign_player_value(player_list):
  choices = ["Rock", "Paper", "Scissors"]
  player_dictionary = {i: random.choice(choices) for i in player_list}
  print(player_dictionary)

This way you can get

In [4]: assign_player_value(["P1", "P2", "P3"])
{'P1': 'Scissors', 'P2': 'Rock', 'P3': 'Scissors'}

You are getting generator because of tuple comprehension (random.choice(choices) for p in range(number_of_players))

CodePudding user response:

you can do it like this:

>>> import random
>>> def assign_players_value(player_list):
...     choices = ["Rock", "Paper", "Scissors"]
...     return dict([(player, random.choice(choices)) for player in player_list])
... 
>>> assign_players_value(["P1", "P2", "P3"])
{'P1': 'Rock', 'P2': 'Rock', 'P3': 'Scissors'}
>>> 

  • Related