Help to begginer

I have this list:

[“Carrot: 123.4, True”, “Sweet potato: 100.0, True”, “Salmon: 120.0, False”]

But every time I can receive different ingredients and different number of ingredients.

What I need to get its dictionary:

{‘Carrot’: {‘nutrition_value’: 123.4, ‘vegan’: True}, ‘Sweet potato’: {‘nutrition_value’: 100.0, ‘vegan’: True}, ‘Salmon’: {‘nutrition_value’: 120.0, ‘vegan’: False}}

result = {}
for ing in ingredients:
    name, data = ing.split(': ') # name = 'Carrot'; data = '123.4, True'
    nutrition, vegan = data.split(', ')
    nutrition = float(nutrition)
    vegan = vegan == 'True'
    result[name] = {‘nutrition_value’: nutrition, ‘vegan’: vegan}

I would recommend using a named tuple instead of a dictionary (more efficient, especially since this data does not need to be changed).

from typing import NamedTuple

class Ingredient(NamedTuple):
    nutrition_value: float
    vegan: bool

    result[name] = Ingredient(nutrition, vegan)
    print("Nutritions:", result[name].nutrition_value, "Is vegan:", result[name].vegan)
1 Like