how can i randomly choose keys in dictionary

Thomas Guettler guettli at thomas-guettler.de
Fri Feb 18 03:35:30 EST 2005


Am Thu, 17 Feb 2005 18:13:46 -0800 schrieb neutrinman:

> Hi,there. How can I choose a key in dictionary randomly?
> 
> Say, random.choice() in lists,
> 
> or in lists:
> lists = [1,2,3,4]
> position = random.range(len(lists))
> word = lists[position]

Hi, try this:

import random

mydict={1: "one", 2: "two"}
print mydict[random.choice(mydict.keys())]


-- 
Thomas Güttler, http://www.thomas-guettler.de/





More information about the Python-list mailing list