vendredi 22 février 2019

How to generate a random dictionary in Python

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
def function(n):
   from random import randrange
   mydict = {}
   for i in range(5):
         key = "key " + str(i)

   value = ['value1', 'value2']






Aucun commentaire:

Enregistrer un commentaire