Проблемы с последней функцией.
У меня есть двухуровневая глубокая таблица различных продуктов с их пищевой ценностью:
Код: Выделить всё
products = {
"almonds": {"protein": 6.0, "fat": 14.2, "carbs": 6.1, "fiber": 3.5, "calories": 164},
"banana": {"protein": 1.3, "fat": 0.4, "carbs": 27.0, "fiber": 3.1, "calories": 105},
"buckwheat": {"protein": 5.7, "fat": 1.0, "carbs": 34.0, "fiber": 4.5, "calories": 155},
"ground beef": {"protein": 24.0, "fat": 13, "carbs": 0, "fiber": 0, "calories": 218}
}
У меня возникли проблемы с сортировкой слов по их ценности (на мой взгляд). Мысль о сохранении значения в виде вложенного списка:
Код: Выделить всё
products = {"banana": [1.3, 0.4, 27.0, 3.1, 105]}
Код: Выделить всё
product = input("Name of a product: ").lower().strip()
macro = input("Name of a macronutrient: ").lower().strip()
# using macro variable and if statements to specify the index of a list
if macro == "protein":
products.keys(product)[0] # running into a problem when calling product here
На данный момент у меня есть следующая функция:
Код: Выделить всё
def _get_nested_val(data, *args):
if args and data:
element = args[0]
if element:
value = data.get(element)
return value if len(args) == 1 else _get_nested_val(value, *args[1:])
Код: Выделить всё
elif initial == "show specifics":
product = input("Enter a name of the product: ").lower().strip()
call = input("Enter a macronutrient: ").lower().strip()
if call == "protein" or call == "fat" or call == "carbs" or call == "fiber":
print(_get_nested_val(products, product, call), "grams of", call, "in", product.capitalize())
elif call == "calories":
print(_get_nested_val(products, product, call), "calories in", product.capitalize())
Код: Выделить всё
def main():
initial = input("What do you want the programm to do? ").lower().strip()
... # other functions are called here, not relevant to the current problem
elif initial == "suggest":
suggest()
def suggest():
req = input("Based on what macronutrient would you like the products to be suggested? ")
if request == "protein":
...
### I would like to see the programm running like something this:
# $ What do you want the programm to do? suggest
# $ Based on what macronutrient would you like the products to be suggested? protein
# The following products are high in protein: Beef, Chicken breast, ...
Подробнее здесь: https://stackoverflow.com/questions/791 ... ested-dict