I am trying to get the following output
water:300ml
milk:200ml
coffee:100g
money:$0
The problem is that ml, g and $ are not part of the dictionary that I need to use and I can't convert the integers in the dictionary to strings because they need do be used in later calculations.
And of course the dollar sign is tricky because it has to be at the front.
I tried this code, but it doesn't work, and I just can't come up with an idea. TIA
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money": 0,
}
for k,v in resources.items():
levels= ['ml', 'ml', 'g', '$']
print(k, ':', v)
for level in levels:
totals = (f'{v}{level}')
print(totals)
CodePudding user response:
If you will reuse this operation, you could define a string.Template
import string
template = string.Template("""water:${water}ml
milk:${milk}ml
coffee:${coffee}g
money:$$${money}""") # first 2 dollar signs are an escape to write the $
print(template.substitute(resources))
Which gives
water:300ml
milk:200ml
coffee:100g
money:$0
This might make it a bit easier to think about how you want the output to look.
The syntax here is to write ${var_name}
, and then have a corresponding key in your dictionary 'var_name'
. When you need to write a dollar sign, you must escape it with a double dollar sign $$
.
CodePudding user response:
You can move the levels list outside of your loop and access it's indices with a simple counter.
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money": 0,
}
levels= ['ml', 'ml', 'g', '$']
count = 0
for k, v, in resources.items():
if k != 'money':
totals = (f'{k}:{v}{levels[count]}')
else:
totals = (f'{k}:{levels[count]}{v}')
print(totals)
count = 1
CodePudding user response:
One of the drawbacks of fstrings is that you can't use delayed expansion. You can always fall back on the old style though.
format ={ 'water' : '%sml', 'milk' : '%sml', 'coffee':'%sg', 'money':'$%s' }
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money": 0,
}
dict ( (k, format [k] % v ) for k,v in ressources.items() )