Home > OS >  How to return stuff from the dictionary and multiply them all?
How to return stuff from the dictionary and multiply them all?

Time:11-20

So I'm trying to multiply every single number that is assigned to each variable in dictionary output and I created a function totalcalories(inputlst) to find it.

So what I'm trying to do is to define a function totalcalories(inputlst) that will return the total number of calories consumed based on every meal you eat.

The calories will be stored in a dictionary like this...

inputlst =  {"Cabbage":"4,2,0", "Carrot":"9,1,5", "Fatty Pork":"431,1,5"}

where the first number will be multiplied by 5, the second will be multiplied by 5 and the third one will be multiplied by 9.

so for instance if Cabbage is called, (its numbers are (4,2,0)), the output should return ((4 * 5) (2 * 5) (0 * 9)), which is 30.

I tried to do it like this, which clearly doesn't work...

def totalcalories(inputlist):
    output = {inputlist}
    g= []
    for x in output:
        g.append(x)
    return g
print(totalcalories(["Cabbage"]))

I'm really new to this, so please try to use dictionaries and simple beginner programming tricks to help me out, Thank you:)

CodePudding user response:

You could use something like this:

sum([x*y for x, y in zip(map(int, inputlst["Cabbage"].split(",")),[5,5,9])])

Essentially, after having parsed the list of inputs into ints, you get their respective multipliers side-by-side and using a list comprehension you multiply them.

The function would be:

def calc(name):
    return sum([x*y for x, y in zip(map(int, inputlst[name].split(",")),[5,5,9])])

CodePudding user response:

Your code attempt currently does none of the things you want it to do, so it may be best to start from scratch.

Firstly, you will want a function that will take an inputted food (as a string), and your dictionary inputlst, so we can begin with the below:

def totalcalories(food, inputlst):
    #calculate calories

Firstly, you're going to need to be able to acess the values associated with your food key in your dictionary. You can do this as below:

inputlst['Cabbage']

Which returns:

'4,2,0'

Your dictionary values are all strings of numbers, which makes things more complicated. It will be easier to use those numbers if you could have them as lists e.g. [4, 2, 0], but we can change the string to a list and remove ',' like below:

values = list(inputlst[food])
values = [x for x in values if x != ',']

So now you have a list of the values ready to be used, so now its a case of multiplying each value by the values you specified above (5, 5 and 9). It might be useful to add these as variables into your function if they are likely to change, but for now I'm going to write it as below:

output = (values[0] * 5)   (values[1] * 5)   (values[2] * 9)

Then you will need to add return output to the end of your function. Hopefully that's enough information for you to be able to put together your function now.

CodePudding user response:

I'm not sure if you have control over your input list or not. But if you do, try converting it to a list of integers instead of a comma separated string. Why? It requires a extra step to convert it to integers for the multiply action.

So turn it into this:

inputlst =  {"Cabbage":[4, 2, 0], "Carrot":[9, 1, 5], "Fatty Pork":[431, 1, 5]}

If you're unable to to this directly, you can easily convert your input into this, using map:

inputlst =  {"Cabbage":"4,2,0", "Carrot":"9,1,5", "Fatty Pork":"431,1,5"}
# Loop over all key and value in your dict.
for key, value in inputlst.items():
    # Split string into the separate numbers.
    new_value = value.split(',')
    # Convert them into integers using ma[.
    # map returns a map object, convert it into a list.
    inputlst[key] = list(map(int, new_value))

print(inputlst) # {'Cabbage': [4, 2, 0], 'Carrot': [9, 1, 5], 'Fatty Pork': [431, 1, 5]}

Then in your code, you don't need to do any conversion of the data. Making it easier for yourself and keeps it simple (KISS approach):

# Define a constant with our multipliers.
MULTIPLIERS = [5, 5, 9]


def totalcalories(list_of_integers):
    total = 0
    # Loop over the integers and keep track of the index of the loop.
    for i, integer_value in enumerate(list_of_integers):
        # Fetch the multiplier we want for this index.
        multiplier = MULTIPLIERS[i]
        # Apply multiply and add it to the total.
        total  = (integer_value * multiplier)
    return total

Which we can then easily call in a for loop:

>>> for key, value in inputlst.items():
>>>     print(key, totalcalories(value))
Cabbage 30
Carrot 95
Fatty Pork 2205

Or of course just with the value you want:

>>> totalcalories(inputlst['Cabbage'])
30
  • Related