How to choose dictionary key randomly based on value in Python

1 Answer

0 votes
import random

dic = {"python": 9, "php": 8, "c": 12, "c++": 5, "c#": 7, "vb": 2}

keys = list(dic.keys())
values = list(dic.values())

random_key = random.choices(keys, weights=values)
print(random_key)

random_key = random.choices(keys, weights=values)
print(random_key)



'''
run:

['c']
['python']

'''

 



answered Dec 3, 2019 by avibootz
...