Pick Dictionary Keys:Values Randomly

Pick dictionary keys:values randomly

A dictionary does not allow for random access of elements without knowing their key. The only solution is to find all Zero elements, store them in a list, and then taking a random selection from them:

import random
zeros = [k for k, v in d.items() if v == "Zero"]
random.sample(zeros, 1000)

how to randomly choose multiple keys and its value in a dictionary python

That's what random.sample() is for:

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

This can be used to choose the keys. The values can subsequently be retrieved by normal dictionary lookup:

>>> d = dict.fromkeys(range(100))
>>> keys = random.sample(list(d), 10)
>>> keys
[52, 3, 10, 92, 86, 42, 99, 73, 56, 23]
>>> values = [d[k] for k in keys]

Alternatively, you can directly sample from d.items().

Python: How do I randomly select a value from a dictionary key?

You can use a list comprehension to loop over your values :

>>> my_dict = {
... "Apple": ["Green", "Healthy", "Sweet"],
... "Banana": ["Yellow", "Squishy", "Bland"],
... "Steak": ["Red", "Protein", "Savory"]
... }
>>> import random
>>> food=[random.choice(i) for i in my_dict.values()]
>>> food
['Savory', 'Green', 'Squishy']

And for print like what you want you can use join function or loop over food and print the elements one by one :

>>> print '\n'.join(food)
Savory
Green
Squishy
>>> for val in food :
... print val
...
Savory
Green
Squishy

How to randomly select a key from a dictionary based on it's float value

As a one liner:

import random

random.seed(100)
d = {'option one': 5.0, 'option two': 5.0, 'option three': 10.0}
picked = random.choices(*zip(*d.items()))[0]
print(picked)
# option one

More broken down:

import random

random.seed(100)
d = {'option one': 5.0, 'option two': 5.0, 'option three': 10.0}
# Key-value pairs in dictionary
items = d.items()
# "Transpose" items: from key-value pairs to sequence of keys and sequence of values
values, weights = zip(*items)
# Weighted choice (of one element)
picked = random.choices(values, weights)[0]
print(picked)
# option one

Note random.choices (which, unlike random.choice, offers a weights parameter) was added on Python 3.6.

Choose dictionary key randomly based on value

Use random.choices with the weights parameter:

random.choices(population, weights=None, *, cum_weights=None, k=1)

Return a k sized list of elements chosen from the population with
replacement. If the population is empty, raises IndexError.

If a weights sequence is specified, selections are made according to
the relative weights. Alternatively, if a cum_weights sequence is
given, the selections are made according to the cumulative weights

import random

d = {"one": 5, "two": 1, "three": 25, "four": 14}
keys = list(d.keys())
values = list(d.values())
random_key = random.choices(keys, weights=values)

print(random_key)
# ['three']

Is there a way to randomly shuffle keys and values in a Python Dictionary, but the result can't have any of the original key value pairs?

A shuffle which doesn't leave any element in the same place is called a derangement. Essentially, there are two parts to this problem: first to generate a derangement of the keys, and then to build the new dictionary.

We can randomly generate a derangement by shuffling until we get one; on average it should only take 2-3 tries even for large dictionaries, but this is a Las Vegas algorithm in the sense that there's a tiny probability it could take a much longer time to run than expected. The upside is that this trivially guarantees that all derangements are equally likely.

from random import shuffle

def derangement(keys):
if len(keys) == 1:
raise ValueError('No derangement is possible')

new_keys = list(keys)

while any(x == y for x, y in zip(keys, new_keys)):
shuffle(new_keys)

return new_keys

def shuffle_dict(d):
return { x: d[y] for x, y in zip(d, derangement(d)) }

Usage:

>>> shuffle_dict({ 'a': 1, 'b': 2, 'c': 3 })
{'a': 2, 'b': 3, 'c': 1}


Related Topics



Leave a reply



Submit