Home > OS >  Creating a random dictionary in python
Creating a random dictionary in python

Time:01-19

I would like to create a random dictionary starting from the following array:

list = [1,2,3,4,5]

In particular, I would like to have as keys of the dictionary all the elements of the array and as corresponding keys, randomly pick some values from that array except the value that corresponds to the key

An example of expected output should be something like:

Randomdict = {1: [2, 4], 2: [1,3,5] 3: [2] 4: [2,3,5] 5: [1,2,3,4]}

And last but not least all keys should have at least 1 value

CodePudding user response:

It can be done with the random module and comprehensions:

from random import sample, randrange

d = {i: sample([j for j in lst if i != j], randrange(1, len(lst) - 1))
     for i in lst}

If you first use random.seed(0) for reproducible data, you will get:

{1: [3, 2], 2: [4, 3], 3: [2, 4], 4: [3, 1]}
{1: [3], 2: [1], 3: [4, 1], 4: [1, 3]}
{1: [3, 2], 2: [3, 4], 3: [4], 4: [2, 3]}

CodePudding user response:

Something like this? Might needs some tweaks

from random import randrange, sample

q = [1, 2, 3, 4, 5]
a = {}
for i in q:
    n = randrange(len(q)-1)
    a[i] = sample(q, n)

print(a)
  •  Tags:  
  • Related