If you want to remove the first element "tikka" and all the elements starting from "Calories" in the given list before storing it into key-value pairs, you can modify the code as follows:
data = ['tikka', '', 'Calories: 200', 'Fat: 11g', 'Carbohydrates: 8g', 'Protein: 15g', 'Sodium: 250mg', 'Fiber: 0g', 'Sugar: 6g']
Find the index of the element starting with "Calories"
calories_index = None
for i, item in enumerate(data):
if item.startswith("Calories"):
calories_index = i
break
# Remove the first element "tikka" and all elements starting from "Calories"
data = data[1:calories_index]
# Create an empty dictionary
food_info = {}
# Iterate over the list
for item in data:
# Split the item by the first occurrence of ':' to separate the key and value
key, value = item.split(':', 1)
# Strip any leading or trailing whitespaces from the key and value
key = key.strip()
value = value.strip()
# Store the key-value pair in the dictionary
food_info[key] = value
# Print the dictionary
print(food_info)
Output:
{'Fat': '11g', 'Carbohydrates': '8g', 'Protein': '15g', 'Sodium': '250mg', 'Fiber': '0g', 'Sugar': '6g'}
After removing the first element "tikka" and all the elements starting from "Calories", the resulting dictionary only contains the key-value pairs starting from "Fat" to "Sugar".
Top comments (0)