Home > Blockchain >  how to take the same random key in a py dictionary?
how to take the same random key in a py dictionary?

Time:12-12

I want take random key in this dict :

{'F' : 'FF', 'B' : 'F[[-B][ B]]F[ FB]-B','B': 'F[-B]F[-FB] B',}

I have same key this is normal and if the key is 'B' I want one of the two associated values to be returned to me. i.e. if the key is 'B' the result must be'F[[-B][ B]]F[ FB]-B'or'F[-B]F[-FB] B'randomly and i didn't see how to make that.

CodePudding user response:

A dictionary can only have unique keys.

You could use a dictionary of lists and get a random choice using random.choice:

d = {'F' : ['FF'], 'B': ['F[[-B][ B]]F[ FB]-B', 'F[-B]F[-FB] B']}

import random
random.choice(d['B'])

output: 'F[[-B][ B]]F[ FB]-B' or 'F[-B]F[-FB] B' (50% chance each)

CodePudding user response:

Using random.choice is not a bad idea at all. I wrote up a little class that uses a dictionary of lists to achieve a similar result.

import random

class randomizer:
    def __init__(self):
        self.data = {}
    def add(self,k,v):
        try:
            self.data[k].append(v)
        except:
            self.data[k] = [v]
    def get(self,k):
        i = int(random.random()*len(self.data[k]))
        # ^ this is where you could use random.choice
        return(self.data[k][i])

d = randomizer()
d.add("a",1)
d.add("a",2)
d.add("a",3)
d.add("b",4)
d.add("b",5)
for k in range(0,5):
    print(d.get("a"))
for k in range(0,5):
    print(d.get("b"))

CodePudding user response:

Your dictionary will have only one B key but if you it a list of dictionaries, so you use random.sample to select a B value randomly:

from random import sample
lst = [{'F' : 'FF'}, {'B' : 'F[[-B][ B]]F[ FB]-B'},{'B': 'F[-B]F[-FB] B'}]
out = sample([d['B'] for d in lst if 'B' in d],1)
  • Related