Home > Mobile >  Python - How to randomly choose items from hash?
Python - How to randomly choose items from hash?

Time:03-05

I have file elements.py where I have defined some elements

def get_random_element():
first = {
 a : 1,
 b : 2
}

second = {
 a : 2,
 b : 3,
 c : 4,
 d : 6,
 ....
}
...
return [ first, second, ... ]

In main python files, I am choosing random element from elements.py

from resources.elements import get_random_elements
...
element = random.choice(get_random_elements())

My problem is, that if it randomly choose second element (only second), I don't want there all items (a,b,c,d...), I want to choose it also randomly. So for example, if random generator takes second element, I want to also randomly choose its items e.g.:

a : 2
c : 4
d : 6
g : 9
...

Could someone help me, how to do it?

CodePudding user response:

Randomize the random choice again!

import random

def get_random_element():
    first = dict(a=1, b=2)
    second = dict(a=2, b=3, c=4, d=6, )
    return [first, second]


# choose a random dict
choice = random.choice(get_random_element())
# choose some random keys, and generate the selected values
elements = {sample: choice.get(sample) for sample in random.sample(list(choice), random.randint(1, len(choice)))}
print(elements)

CodePudding user response:

I have to make some assumptions on what you are asking but I will try to help.

basically what you are doing with

element = random.choice(get_random_elements())

is taking a random dictionary from the list of dictionaries you return from get_random_elements()

so you are randomly selecting a dictionary but I assume u want to take a random value of a random dictionary, now to achieve this you can do it in two ways:

1st way:

in elements.py

modify the return value of get_random_elements()

return random.choice([ first, second, ... ])

this way you are effectively returning a random dictionary from the function

make sure to import random in elements.py

in main.py

assuming you want to return a random value of the random dictionary:

element = random.choice(get_random_elements().values())

note that .values() returns a list containing the values of the dictionary

2nd way:

in main.py

element = random.choice(random.choice(get_random_elements()).values())

does the same thing as above but i would not recommand this since it doesnt maintain coherence with the function name and what you are effectively doing

  • Related