Проблемы с последней функцией.
У меня есть двухуровневый глубокий список разных продуктов с их пищевой ценностью, например — банана:
Код: Выделить всё
products = {"banana": {"protein": 1.3, "fat": 0.4, "carbs": 27.0, "fiber": 3.1, "calories": 105}}
У меня возникли проблемы с сортировкой слов по их ценности (на мой взгляд). Мысль о сохранении значения в виде вложенного списка:
Код: Выделить всё
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())
Я проверил много других вопросов о переполнении стека, но мне не удается заставить мою программу работать так, как я хочу.
Подробнее здесь: https://stackoverflow.com/questions/791 ... ested-dict