How to randomly pick an item from a dictionary in Python?

4

I would like to know how to randomly pick an item from a Python dictionary?

For example:

I have the dictionary

dic = {'Pedro': 99, 'João': 19, 'Rosa': 35, 'Maria': 23}

I need to choose an item randomly.

    
asked by anonymous 28.12.2016 / 17:05

1 answer

4

One way to do this in Python 3 is to get a view of the dictionary items and use the random.choice function to choose an element.

import random
dic = {'Pedro': 99, 'João': 19, 'Rosa': 35, 'Maria': 23}
name, id = random.choice(list(dic.items()))

Font : SOen - How to get random value in python dictionary

    
28.12.2016 / 17:18