0

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.

5
  • 2
    Note that you have 'B' key twice. The first value for that key will be lost and you can never return it. Consider to make this dict of lists. Commented Dec 11, 2021 at 20:18
  • Yes I know then how I do so that the two values and a 50% chance of being returned Commented Dec 11, 2021 at 20:22
  • 1
    The dictionary is invalid to begin with. Instead, you probably want to have the key be B, and the values be a list ['F[[-B][+B]]F[+FB]-B', 'F[-B]F[-FB]+B']. To randomly sample a value, query into the key and select one of the values in the list. Commented Dec 11, 2021 at 20:23
  • @JakeTae, actually the dict literal is valid and will not raise error, only that last seen wins and the first value for key B will be lost Commented Dec 11, 2021 at 20:30
  • @buran, you're right, it would initialize fine. I meant to say that it's invalid from a user point of view (it's not what was intended). Thanks for pointing it out though! Commented Dec 11, 2021 at 23:16

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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")) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.