Skip to content
Advertisement

Generating dictionary does not always work

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.

import random

class practica6:

#Create our constructor
    def __init__(self) -> None:
        # Initialize users dictionary
        self.usuarios = {}
        #List of possible names the users can take
        self.nombres = ['Mario', 'Pepe', 'Angel', 'Joaquin', 'Jesus', 'Edson', 'Emilio', 
        'Eli', 'Francisco', 'Sergio', 
        'Erick', 'David', 'Liam', 'Noah', 'Oliver', 'William', 'James', 'Benjamin', 'Lucas', 
        'Henry', 'Alexander', 
        'Mason', 'Michael', 'Ethan', 'Mateo', 'Sebastian', 'Jack', 'Peter', 'Josh', 
        'Patricia', 'Luis', 'Gerardo', 'Carmen']


    def generar_diccionario_usuarios(self, numero_usuarios : int):
        #Generate a dictionary with random names (keys) and random priority (values) keys : 
        #values
        for i in range(numero_usuarios):
            self.usuarios[random.choice(self.nombres)] = random.randint(1, 10)
        #DEBUG : Print our users dictionary
        print(self.usuarios)

#Test app
practica = practica6()
n = 10
print('Usuarios:')
practica.generar_diccionario_usuarios(n)

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:

for nombre in random.sample(self.nombres, numero_usuarios):
    self.usuarios[nombre] = random.randint(1, 10)

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement