Search code examples
pythonfunctiondictionarykeykey-value

Updating key values in dictionaries


I am trying to write code for the following: The idea is to have a storage/inventory dictionary and then have the key values be reduced by certain household tasks. E.g. cleaning, cooking etc.

This would be the storage dictionary:

cupboard= {"cookies":30,
    "coffee":3, 
    "washingpowder": 5,
    "cleaningspray": 5,
    'Pasta': 0.5,
    'Tomato': 4, 
    'Beef': 2, 
    'Potato': 2, 
    'Flour': 0.2, 
    'Milk': 1, 
    "Burger buns": 6}

now this is the code that I wrote to try and reduce one single key's value (idea is that the action "cleaning" reduces the key "cleaning spray" by one cleaning unit = 0.5

cleaning_amount = 0.5
def cleaning(room):
    while cupboard["cleaningspray"] <0.5:
        cleaned = {key: cupboard.get(key) - cleaning_amount for key in cupboard}
        return cupboard
    
livingroom = 1*cleaning_amount

cleaning(livingroom)
        
print(cupboard)

but it returns this, which is the same dictionary as before, with no updated values

{'cookies': 30, 'coffee': 3, 'washingpowder': 5, 'cleaningspray': 5, 'Pasta': 0.5, 'Tomato': 4, 'Beef': 2, 'Potato': 2, 'Flour': 0.2, 'Milk': 1, 'Burger buns': 6}

Can anybody help?

Thank you!!

picture attached to see indents etc.

Image 1


Solution

  • I guess you want to decrease the "cleaningspray" amount depending on the room size (or other factors). I would do it like this:

    cleaning_amount = 0.5
    
    
    def cleaning(cleaning_factor):
        if cupboard["cleaningspray"] > 0.5:
            # reduce the amount of cleaning spray depending on the cleaning_factor and the global cleaning_amount
            cupboard["cleaningspray"] -= cleaning_factor * cleaning_amount
    
    
    livingroom_cleaning_factor = 1
    
    cleaning(livingroom_cleaning_factor)
    
    print(cupboard)
    
    

    Output:

    {'cookies': 30, 'coffee': 3, 'washingpowder': 5, 'cleaningspray': 4.5, 'Pasta': 0.5, 'Tomato': 4, 'Beef': 2, 'Potato': 2, 'Flour': 0.2, 'Milk': 1, 'Burger buns': 6}