Start Your Journey with Linux Command Line
Welcome to this comprehensive guide for Python beginners! If you are learning how to work with lists, dictionaries, and loops, this post will help you build practical skills using a real-world example: nutrition facts for fruits.
Below is a sample dataset of fruits and their calorie values, formatted as a Python list of dictionaries. This structure is ideal for coding exercises, projects, or even building your own nutrition calculator. You can expand this list, add new fruits, or use it as a foundation for more advanced Python tasks.
fruits = [
{'name': 'Apple', 'calories': 130},
{'name': 'Avocado', 'calories': 50},
{'name': 'Banana', 'calories': 110},
{'name': 'Cantaloupe', 'calories': 50},
{'name': 'Grapefruit', 'calories': 60},
{'name': 'Grapes', 'calories': 90},
{'name': 'Honeydew Melon', 'calories': 50},
{'name': 'Kiwifruit', 'calories': 90},
{'name': 'Lemon', 'calories': 15},
{'name': 'Lime', 'calories': 20},
{'name': 'Nectarine', 'calories': 60},
{'name': 'Orange', 'calories': 80},
{'name': 'Peach', 'calories': 60},
{'name': 'Pear', 'calories': 100},
{'name': 'Pineapple', 'calories': 50},
{'name': 'Plums', 'calories': 70},
{'name': 'Strawberries', 'calories': 50},
{'name': 'Sweet Cherries', 'calories': 100},
{'name': 'Tangerine', 'calories': 50},
{'name': 'Watermelon', 'calories': 80}
]
fruits list into your Python code editor.for loop to search for a fruit by name and print its calories.get_calories(fruit_name) function that takes a fruit name and returns its calorie value.def get_calories(fruit_name): for fruit in fruits: if fruit['name'].lower() == fruit_name.lower(): return fruit['calories'] return None # Test lookup item = input("Item: ").strip() calories = get_calories(item) if calories is not None: print(f"Calories: {calories}") else: print("Fruit not found.")
For more hands-on tutorials, source code breakdowns, and Python learning resources, check out our YouTube channel @CodeSecureTech!
When working with structured data in Python, a list of dictionaries is one of the most practical and readable formats. Each dictionary represents a single record (in this case, a fruit), and each key-value pair within the dictionary stores a specific attribute (the fruit's name and its calorie count). This structure mirrors how data is organized in spreadsheets and databases, making it a natural choice for beginners who are transitioning from manual data entry to programmatic data handling.
The advantages of this format become clear when you start writing functions to query the data. You can loop through the list, access each dictionary by key, and perform comparisons or calculations. For example, finding the calorie count of a specific fruit requires a simple for loop with an if condition that checks the name key. This pattern of iteration and comparison is the foundation of most data processing tasks in Python.
One useful exercise is to write a function that finds all fruits with fewer than a certain number of calories. This requires iterating through the list, checking the calories value, and collecting matching results in a new list. Another exercise is to calculate the average calorie count across all fruits using the sum() and len() functions. These exercises reinforce core Python concepts: loops, conditionals, function definitions, and list manipulation.
sum() and len() functions make calculations like averages straightforward.A list of dictionaries is more readable and self-documenting. With dictionaries, you access data by meaningful key names like fruit['name'] rather than relying on numeric indices like fruit[0]. This makes the code easier to understand and maintain, especially when working with complex datasets.
Append a new dictionary to the list using fruits.append({'name': 'Mango', 'calories': 200}). This adds the new record at the end of the list, and you can immediately access it using the same loop-based approach used for existing entries.
Yes. Use the sorted() function with a lambda function as the key: sorted(fruits, key=lambda x: x['calories']). This returns a new list of dictionaries sorted from lowest to highest calorie count without modifying the original list.
Your function should handle this gracefully by returning None or printing a "not found" message. This is good practice for building robust programs that do not crash when encountering unexpected input.
Simply add more key-value pairs to each dictionary, such as 'sugar', 'fiber', or 'vitamin_c'. The same loop and conditional patterns you use for name and calories will work for any additional fields you add.
Comments
Post a Comment
Your opinion matters, your voice makes us proud and happy. Your words are our motivation.