Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way in Python to update multiple random values in dictionary?

I am working on a schedule generator, and I need to randomly put two days off into it. I came up with a solution, however I noticed that randinit method can put two days off on one day, so this option doesn’t work for me.

import random

schedule = {1: "9:00 - 17:00", 2: "9:00 - 17:00", 3: "16:00 - 00:00", 4: "16:00 - 00:00", 5: "16:00 - 00:00", 6: "16:00 - 00:00", 7: "16:00 - 00:00"}
days_off = {random.randint(1, 7): "X", random.randint(1, 7): "X"}

schedule.update(days_off)

So I am thinking that there should be an easier way to make it work without hardcoding, but I cannot really find it.

Will appreciate any help!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What you are looking for is random.sample(), which allows you to randomly select multiple different values from a given population:

for d in random.sample(range(1, 7+1), k=2):
    schedule[d] = "X"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading