/
stendal
/
Files
Обзор
Документация
Войти
/
stendal
/
Files
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
task_1.py
61 строка
2 KB
stendal
upload files
05 июл 2025, 21:09
05 июл 2025, 21:09
8bf78cf
Код
Авторство
О чём код?
def read_cookbook(file_path): """Reads a file with recipes and returns a dictionary with data. Args: file_path: path to the recipe file Returns: dictionary in format: { 'Dish Name': [ {'ingredient_name': str, 'quantity': int, 'measure': str}, ... ], ... } """ cook_book = {} with open(file_path, 'r', encoding='utf-8') as f: while True: dish_name = f.readline().strip() if not dish_name: break ingredients_count = int(f.readline().strip()) ingredients = [] for _ in range(ingredients_count): ingredients_line = f.readline().strip() if not ingredients_line: print(f"Ингредиент отсутствует в {dish_name}") break name, quantity, measure = map(str.strip, ingredients_line.split('|')) ingredients.append({ 'ingredient_name': name, 'quantity': int(quantity), 'measure': measure }) # Skip empty line between dishes f.readline() cook_book[dish_name] = ingredients return cook_book # Usage example if __name__ == "__main__": cook_book = read_cookbook("recipes.txt") print("cook_book = {") for i, (dish, ingredients) in enumerate(cook_book.items()): print(f" '{dish}': [") for j, ing in enumerate(ingredients): end_char = "," if j < len(ingredients) - 1 else "" print( f" {{'ingredient_name': '{ing['ingredient_name']}', 'quantity': {ing['quantity']}, 'measure': '{ing['measure']}'}}{end_char}") end_dish = "," if i < len(cook_book) - 1 else "" print(f" ]{end_dish}") print("}")