Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Picking random values multiple times from the same dict.

Tags:

python

I'm trying to pick a random value from a dict. and then pick a second value from the same dict. guaranteeing that it is different.

def pick_value():
    value, attribute = random.choice(list(my_dict.items()))
    return(value, attribute)

If I call the function it works, however there is no guarantee that the second time I call it the value will be different than the first so I tried the following.

my_value_list = []

val1, attr1 = pick_value()
my_value_list.append(val1)

val2, attr2 = pick_value()
if val2 in my_value_list:
    val2, attr2 = pick_value()

I still get matching values occasionally. I tried replacing the if val2 in statement with while val2 in and still no luck. Am I misunderstanding something simple?

like image 391
BrettJ Avatar asked Aug 02 '26 06:08

BrettJ


2 Answers

If you need exactly two values (or any fixed number you know in advance), use random.sample(). That's what it's for: Sampling "without replacement", i.e. once you've picked an element from the list, it is no longer available to be picked again.

samples = random.sample(list(mydict.items()), 2)
attr1, val1 = samples[0]
attr2, val2 = samples[1]
like image 104
alexis Avatar answered Aug 03 '26 19:08

alexis


As alexis has suggested, random.sample() is the right tool for this job, but for the sake of completeness, if you need to pick up random fields in a iterative/lazy fashion, you can do it yourself by:

def pick_random_destructive(data):
    key = random.choice(data.keys()) if data else None
    return key, data.pop(key, None)

However, that WILL modify the dict you pass to it. If you want a non-modifying iterative method you can create a generator like:

def pick_random_nondestructive(data):
    keys = random.shuffle(data.keys())
    while keys:
        key = keys.pop()
        yield key, data[key]
like image 20
zwer Avatar answered Aug 03 '26 21:08

zwer



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!