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.
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.
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()))