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.

JavaScript

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
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement