I need to create a dictionary with key and random values given a scope, i.e.
{key 1: value1, key 2: value2, key 3: value1, key 4: value 1, key 5: value 1}
or
{key 1: value2, key 2: value1, key 3: value1, key 4: value 1, key 5: value 1}
or
{key 1: value1, key 2: value1, key 3: value1, key 4: value 1, key 5: value 2}
...and so on
As you can see, the dictionary has the pattern below:
value1
and value2
), but value2
can only appear 1 time randomly in any key. The remaining values will be value1
.Code:
def function(n):
from random import randrange
mydict = {}
for i in range(5):
key = "key " + str(i)
value = ['value1', 'value2']
Just default all the values to value1
first, and then randomly pick one key to change to value2
:
def function(n):
from random import randrange
values = ['value1', 'value2']
mydict = {"key " + str(i): values[0] for i in range(n)}
mydict["key " + str(random.randrange(n))] = values[1]
return mydict
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With