I’m a bit of a newbie in Python but is it possible to do the following?
I want to create a dictionary,test_tube, that shows what liquid is in it and the quantity of it. With the function add_liquid I want to add a new liquid or more of the previously used liquid to the test tube, without the use of defaultdicts.
Def add_liquid(test_tube,liquid,milliliters=0):
test_tube[liquid] = milliters
return test_tube
#update of previous test tube and memorize new test tube
>>>add_liquid(test_tube,'water',10)
{'water':10}
>>>more_water=add_liquid(test_tube,'water',5)
>>>more_water
{'water':15}
>>>add_liquid(test_tube,'ethanol',1)
{'ethanol':1, 'water':15}
Python must somehow memorize what the previously quantity of liquid was in the test_tube.
Any advice would be appreciated!
If I understand your question correctly, you just need to check if the liquid is already in there, and if so, add the amounts.
Another way to formulate this is to set the value to the sum of the current value or 0 of there is no, and milliliters:
Note that you need to either define your function so that it modifies the dictionary that you pass in (and then you shouldn’t really return anything), or that it returns a modified copy of it.