5
I would like to know how to randomly choose an item from a Python dictionary?
For example:
I have the dictionary
dic = {'Pedro': 99, 'João': 19, 'Rosa': 35, 'Maria': 23}
and need to choose an item randomly.
5
I would like to know how to randomly choose an item from a Python dictionary?
For example:
I have the dictionary
dic = {'Pedro': 99, 'João': 19, 'Rosa': 35, 'Maria': 23}
and need to choose an item randomly.
4
One way to do this in Python 3 is to get a view of the dictionary items and use the function random.choice
to choose an element.
import random
dic = {'Pedro': 99, 'João': 19, 'Rosa': 35, 'Maria': 23}
name, id = random.choice(list(dic.items()))
Source: Soen - How to get a Random value in python Dictionary
Browser other questions tagged python python-3.x
You are not signed in. Login or sign up in order to post.
By item you mean the key, the value or both?
– Anthony Accioly
Both key and value
– Dérick Ramos