简体   繁体   中英

Dictonary DataType with random in Python

I am trying to create a dictionary data type using python 3.2. I am using random method to randomly choose a values in the mydict and print out the value. However, I would like to print the key as well (eg Animal: elephant) but I only manage to print either the key or the values. How do I go about it?

mydict = {'Animal': ('elephant', 'giraffe', 'rhinoceros', 'hippopotamus', 'leopard'),
          'Fruit': ('strawberry', 'mango', 'watermelon', 'orange', 'durian')}
random_word = random.choice(random.choice(list(mydict.values())))

mydict.values() , unsurprisingly, gives you the values. You can use mydict.items() to get the key/value pairs (as tuples).

Edit: it sounds like you're trying to do something like this:

category = random.choice(list(mydict.keys())
item = random.choice(mydict[category]))
print category, item

mydict.values() will print the values , it may not be what you expect:

>>> random.choice(mydict.values())
('strawberry', 'mango', 'watermelon', 'orange', 'durian')
>>> random.choice(mydict.values())
('elephant', 'giraffe', 'rhinoceros', 'hippopotamus', 'leopard')

I think what you really want to do is to combine all the values of all the keys, select one of the values at random, then find out what key it belongs to. To do that, first you need to select all the values to randomize them:

>>> for i in mydict.values():
...    for v in i:
...       values_list.append(v)
...
>>> values_list
['strawberry', 'mango', 'watermelon', 'orange', 'durian', 'elephant', 'giraffe',
 'rhinoceros', 'hippopotamus', 'leopard']

Now, you are able to get random values:

>>> random.choice(values_list)
'leopard'
>>> random.choice(values_list)
'strawberry'
>>> random.choice(values_list)
'hippopotamus'

Next step is to find out which keys this belongs to:

>>> i = random.choice(values_list)
>>> ''.join("%s: %s" % (k,i) for k in mydict if i in mydict[k])
'Fruit: watermelon'

By default when you iterate over a dictionary, you will get the keys:

>>> for i in mydict:
...    print i
...
Fruit
Animal

This line ''.join("%s: %s" % (k,i) for k in mydict if i in mydict[k]) is the long version of this loop:

i = random.choice(values_list)
for k in mydict:
    if i in mydict[k]:
       print "%s: %s" % (k,i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM