Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random dictionary?

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:

  • the key is generated from the input number of the function, if I input 5, I have 5 keys, if I input 3, I have 3 keys
  • the value has only 2 different values (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']
like image 869
potentialwjy Avatar asked Oct 19 '25 02:10

potentialwjy


1 Answers

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
like image 136
r.ook Avatar answered Oct 21 '25 15:10

r.ook



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!