Home > OS >  How can I make a dictionary out of this?
How can I make a dictionary out of this?

Time:11-20

So I'm trying to make a dictionary out of a given input such as

["Cabbage:4,2,0", "Carrot:9,1,5", "Fatty Pork:431,1,5",
"Pineapple:7,1,0", "Steak Meat:5,20,10", "Rabbit Meat:7,2,20"]

and for every word before the ":" in each word in the string, I'm trying to seperate the string and putting it as a dictionary and also multiply the first and second number by 5 and the last number by 9 and add all of them... so like I'm trying to make my output look like this...

["Cabbage": {30}, "Carrot": {95}.....]

Here is my attempt at doing the code, which didn't work...

def dictcal(calories):
    d = dict()
    for r in calories:
        i = dict()
        r_ = r.split(':')
        for c_ in r_[1].split(','):
            i_ = c_.split('*')
            i[i_[0].strip()] = int(i_[1])
        d[r_[0]] = i
    return d

This clearly doesn't work so, can anyone please explain and guide me to what should I do to ensure that this output gets returned correctly??

Please use the most basic method of coding as possible

CodePudding user response:

# Data you provided
data = ["Cabbage:4,2,0", "Carrot:9,1,5", "Fatty Pork:431,1,5",
"Pineapple:7,1,0", "Steak Meat:5,20,10", "Rabbit Meat:7,2,20"]

calorie_dict = {} # Dictionary that stores the foods and calories in key-value pairs

# Iterate over each element in the list
for el in data:

  food, values = el.split(':') # Split it into the food name, and the values after it
  a, b, c = values.split(',') # Seperate the three numbers

  # Multiply them by 5, 5, and 9, and then sum them up
  calories = (int(a) * 5)   (int(b) * 5)   (int(c) * 9)

  calorie_dict[food] = calories # Add a new entry to the dictionary

print(calorie_dict) # Print out the dictionary

If you don't want to use multiple assignment:

data = ["Cabbage:4,2,0", "Carrot:9,1,5", "Fatty Pork:431,1,5",
"Pineapple:7,1,0", "Steak Meat:5,20,10", "Rabbit Meat:7,2,20"]

calories = {}

for el in data:
  terms = el.split(':')
  nums = terms[1].split(',')
  calories = (int(nums[0]) * 5)   (int(nums[1]) * 5)   (int(nums[2]) * 9)

  calories[terms[0]] = terms[1]

print(calories)

CodePudding user response:

You were getting there, up to the split on '*'. At that point you have the numbers and need to perform the multiplications, accumulate the total and finally feed the dictionary.

Here's an example, trying to make it as basic as possible, ...

L = ["Cabbage:4,2,0", "Carrot:9,1,5", "Fatty Pork:431,1,5",
     "Pineapple:7,1,0", "Steak Meat:5,20,10", "Rabbit Meat:7,2,20"]

d = dict()
for s in L:                      # run through each string
    food,numbers = s.split(':')  # separate name from numbers
    total = 0                    # result of sum
    index = 0                    # position of number/multiplier
    for n in numbers.split(','): # get each number as a string
        multiplier = (5,5,9)[index]        # chose corresponding multiplier
        total = total   int(n)*multiplier  # multiply and add to total
        index = index   1                  # advance to next multiplier
    d[food] = {total}

print(d)
{'Cabbage': {30}, 'Carrot': {95}, 'Fatty Pork': {2205}, 
 'Pineapple': {40}, 'Steak Meat': {215}, 'Rabbit Meat': {225}}

The more advanced version could look like this:

d = {food:{sum(m*int(n) for m,n in zip([5,5,9],numbers.split(',')))}
     for s in L for food,numbers in [s.split(":")]}
  • Related