Random from Dictionary

Peter Hansen peter at engcorp.com
Thu Oct 18 23:34:18 EDT 2001


Tim Payne wrote:
> 
> In article <9qml3o$ovl8k$1 at ID-11957.news.dfncis.de>, Emile van Sebille
> <emile at fenx.com> wrote:
> 
> > Maybe choice in random helps out.
> 
> I've always gotten this error when trying choice. I figured you just
> couldn't use it on a dictionary, but maybe something else is wrong with
> my install?
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "/usr/lib/python2.1/random.py", line 329, in choice
>     return seq[int(self.random() * len(seq))]
> KeyError: 1

>>> import random
>>> print random.choice.__doc__
Choose a random element from a non-empty sequence.
>>> random.choice([1, 2])
2
>>> dict = { 'x' : 4, 'y' : 6 }
>>> random.choice(dict)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "c:\python21\lib\random.py", line 329, in choice
    return seq[int(self.random() * len(seq))]
KeyError: 1
>>> random.choice(dict.keys())
'x'

In the Python reference manual, the "standard type hierarchy"
indicates that a Dictionary is a type of Mapping which is
not a Sequence.  The __doc__ string from random.choice asks
for a sequence, so you are right that you can't use it
on a dictionary.  dict.keys() works...

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list