choosing a random element from a dictionary
Sean Ross
sross at connectmail.carleton.ca
Wed Feb 5 21:13:20 EST 2003
here's a couple of ways:
import random # all of these ways require this module
m = {"hello":"world", "how":"are", "you":"today"}
pick = random.choice(m.keys())
m[pick]
or, if you want a function
def pick(m):
"returns a random element from dictionary m"
return m[random.choice(m.keys())]
or, maybe you want both the key and the value...
def pick(m):
"returns a random (key, value) pair from dictionary m"
return random.choice(m.items())
hope that helps,
Sean
"Yuval" <yuvalfeld at hotmail.com> wrote in message
news:6ca96053.0302051630.3ec20056 at posting.google.com...
> Is there a function that picks a random element from a dictionary? To
> my understanding the popitem() method does that, but it also removes
> it from the dictionary. Of course I can use popitem() and add it back
> directly, but is there any other way of doing so?
>
> Thanks.
More information about the Python-list
mailing list