Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading