I am trying to generate a dictionary automatically with a for loop (i < numero_usuarios), the keys are taken from a list with names, and the values are randomly generated with a random.randint(1, 10), the problem is that it does not always generate the amount I want.
For instance, I want to create 10 users(usuarios), it sometimes creates 7, 8 or 9, but rarely 10.
Code below.
JavaScript
x
31
31
1
import random
2
3
class practica6:
4
5
#Create our constructor
6
def __init__(self) -> None:
7
# Initialize users dictionary
8
self.usuarios = {}
9
#List of possible names the users can take
10
self.nombres = ['Mario', 'Pepe', 'Angel', 'Joaquin', 'Jesus', 'Edson', 'Emilio',
11
'Eli', 'Francisco', 'Sergio',
12
'Erick', 'David', 'Liam', 'Noah', 'Oliver', 'William', 'James', 'Benjamin', 'Lucas',
13
'Henry', 'Alexander',
14
'Mason', 'Michael', 'Ethan', 'Mateo', 'Sebastian', 'Jack', 'Peter', 'Josh',
15
'Patricia', 'Luis', 'Gerardo', 'Carmen']
16
17
18
def generar_diccionario_usuarios(self, numero_usuarios : int):
19
#Generate a dictionary with random names (keys) and random priority (values) keys :
20
#values
21
for i in range(numero_usuarios):
22
self.usuarios[random.choice(self.nombres)] = random.randint(1, 10)
23
#DEBUG : Print our users dictionary
24
print(self.usuarios)
25
26
#Test app
27
practica = practica6()
28
n = 10
29
print('Usuarios:')
30
practica.generar_diccionario_usuarios(n)
31
Advertisement
Answer
In a dictionary, a key cannot appear multiple times, and all attempts to insert a key which exists already will result in overwriting the stored value.
random.choice
, being a draw with replacement, can return the same user multiple times. You need to use random.sample
, which simulates a draw without replacement:
JavaScript
1
3
1
for nombre in random.sample(self.nombres, numero_usuarios):
2
self.usuarios[nombre] = random.randint(1, 10)
3