Home > OS >  How to make random number values for a dictionary that stay the same
How to make random number values for a dictionary that stay the same

Time:09-06

Title isn't great, sorry.

I am new to python and I am playing around with dictionaries to further my understanding of them.

To practice, I am making a football team of 11 players. Each player is a dictionary stored in a list.

So each player will have its own dictionary but all the keys will be the same throughout, it's just the values that will change.

I have made the players positions and now I want to add the age of the player. This is what I have:

footballers = []

for populating in range(11): #populating = to get footballers
    new_player = {"position": 'goalkeeper',}
    footballers.append(new_player)

for baller in footballers[1:5]:
    baller["position"] = 'defender'
    print (baller)

for player in footballers[5:8]:
    player["position"] = "midfield"

for player in footballers[8:11]:
    player["position"] = "forward"
    
import random
for baller in footballers:
    baller["age"] = random.randint (17, 34)
    print (baller)

This works and I get the desired result. However, the age changes every time I run the code.

How would I make it so that I run it once and the value of the key stays the same?

I know I could just type the ages out myself but if I wanted to populate a whole league, I'm not doing that.

I've tried other ways such as making the age:value in another list of dictionaries but I couldn't figure out how to put the 2 together.

Is there something I'm missing here?

Thanks

CodePudding user response:

A seed allows to 'randomly' populate a list with the same values every call.
It's important to have the seed outside the loop.

import random  # good practice is to have imports at the top

footballers = []

for populating in range(11): 
    new_player = {"position": 'goalkeeper',}
    footballers.append(new_player)

for baller in footballers[1:5]:
    baller["position"] = 'defender'
    print (baller)

for player in footballers[5:8]:
    player["position"] = "midfield"

for player in footballers[8:11]:
    player["position"] = "forward"

random.seed(42)  
# the correct position is anywhere before the loop to have the same ages every call

for baller in footballers:
    ## random.seed(42)  # Wrong position - will result in each player have the same age
    baller["age"] = random.randint (17, 34)
    print (baller)

Notes:

  • When you run your code in jupyter random.seed() needs to be in the same cell as the random call
  • 42 is just an example, you can use any real number
  • Related