How Do I concatenate the items of a list to their corresponding values in the dictionary

Viewed 62

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)
3 Answers

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 $$.

You can move the levels list outside of your loop and access its 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

Edit: You can also use zip to iterate over a dictionary and list at the same time. I think this is more pythonic than the counter above.

resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
    "money": 0,
}

    
levels = ['ml', 'ml', 'g', '$']

for (k, v), level in zip(resources.items(), levels):
    if k != 'money':
        totals = (f'{k}:{v}{level}')
    else:
        totals = (f'{k}:{level}{v}')
    
    print(totals) 

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() ) 
Related