Subtract value from random dictionary key:value - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Subtract value from random dictionary key:value (/thread-19068.html) |
Subtract value from random dictionary key:value - Tolein - Jun-12-2019 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) RE: Subtract value from random dictionary key:value - perfringo - Jun-12-2019 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 |