Python Forum
Subtract value from random dictionary key:value
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Subtract value from random dictionary key:value
#1
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)
Reply
#2
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  subtract 2 datetime string jss 4 703 Oct-19-2023, 02:42 PM
Last Post: Larz60+
  random from python dictionary rwahdan 2 1,956 Jun-18-2021, 09:05 AM
Last Post: rwahdan
  How to subtract the DayOfWeek from date from a integer? DarkCoder2020 2 2,082 May-27-2020, 09:56 PM
Last Post: bowlofred
  Subtract 11 from entire list of quoted numbers Pleiades 1 1,676 Nov-14-2019, 10:26 AM
Last Post: Larz60+
  Trying to subtract datetime, getting error: TypeError: unsupported operand type(s) fo kneesarethebees 1 4,394 Aug-02-2018, 01:39 AM
Last Post: ichabod801
  Subtract Minutes from Datetime.Time tkj80 2 42,936 May-11-2017, 09:56 AM
Last Post: klllmmm

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020