0

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

1
  • 1
    Hi could you provide an expected output please? Commented Jan 19, 2022 at 14:54

2 Answers 2

1

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]}
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.