Debug School

rakesh kumar
rakesh kumar

Posted on

How to store list all elements in key-value pair in database using django

here my list is

['Calories: 200', 'Fat: 11g', 'Carbohydrates: 8g', 'Protein: 15g', 'Sodium: 250mg', 'Fiber: 0g', 'Sugar: 6g']
Enter fullscreen mode Exit fullscreen mode

To store the given list into key-value pairs, you can use a dictionary in Python. Here's an example of how you can do it:

data = ['Calories: 200', 'Fat: 11g', 'Carbohydrates: 8g', 'Protein: 15g', 'Sodium: 250mg', 'Fiber: 0g', 'Sugar: 6g']

# 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

 chat_message = Recipe(about=food_info)
    chat_message.save()
Enter fullscreen mode Exit fullscreen mode

output

print(food_info)
Enter fullscreen mode Exit fullscreen mode
{'tikka': '', 'Calories': '200', 'Fat': '11g', 'Carbohydrates': '8g', 'Protein': '15g', 'Sodium': '250mg', 'Fiber': '0g', 'Sugar': '6g'}
Enter fullscreen mode Exit fullscreen mode

In the resulting dictionary, each key corresponds to the label in the list, and the value corresponds to the corresponding information. Note that the empty string element in the list is stored as an empty value ('') in the dictionary.

Top comments (0)