Reputation: 111
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 (e.g. 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())))
Upvotes: 1
Views: 215
Reputation: 251378
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
Upvotes: 4
Reputation: 174624
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)
Upvotes: 0