Python Forum

Full Version: Subtract value from random dictionary key:value
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I am having trouble getting my code to work. I am attempting to lookup a random key:value and then later in the code I would like to subtract a number from the value of that key:value that was generated randomly. This is what I have so far.

import random

fruit = {'apples' : 10, 'oranges' :20}
random_fruit = random.choice(list(fruit.items()))
print(random_fruit)
random_fruit -= 3
print(random_fruit)
random_fruit is in dictionary; you actually don't need items, keys is sufficient:

>>> fruit = {'apples' : 10, 'oranges' :20}                                 
>>> random_fruit = random.sample(fruit.keys(), 1)[0]                       
>>> random_fruit                                                           
'oranges'
>>> fruit[random_fruit] -= 3                                               
>>> fruit[random_fruit]                                                    
17