Debug School

rakesh kumar
rakesh kumar

Posted on

How to get list of all elements where list of elements starts with particular element in django

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']
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

{'Fat': '11g', 'Carbohydrates': '8g', 'Protein': '15g', 'Sodium': '250mg', 'Fiber': '0g', 'Sugar': '6g'}
Enter fullscreen mode Exit fullscreen mode

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)