Home > Software design >  Replacing items in a list of dictionaries
Replacing items in a list of dictionaries

Time:05-16

I have the following list of dictionaries:

menu = [{"food": "basic lasagna", "description": "basic lasagna takes tomato sauce and ground beef ."}, {"food": "carbonara pasta", "description": "there are many types of pasta in this world, but carbonara pasta is one of the best ."}, {...}, ...]

I have to highlight the food in the description with tags <food> food </food>, but I don't know how to do this without complicating with indexes. My initial idea was:

for item in menu:
    tag = item["food"]
    if item["food"] in item["description"]:
        i = tag.index()
        tagging = "<food> "   tag   "</food>"
    

But then I got stuck because I don't really know how to replace the item. Any suggestions?

CodePudding user response:

IIUC, what you're after can be done with the replace method:

import json
menu = [{"food": "basic lasagna", "description": "basic lasagna takes tomato sauce and ground beef ."}, {"food": "carbonara pasta", "description": "there are many types of pasta in this world, but carbonara pasta is one of the best ."}]

for item in menu:
    item["description"] = item["description"].replace(item['food'], "<food>"   item['food']   "</food>")

print(json.dumps(menu, indent=4)) 

Output:

[
    {
        "food": "basic lasagna",
        "description": "<food>basic lasagna</food> takes tomato sauce and ground beef ."
    },
    {
        "food": "carbonara pasta",
        "description": "there are many types of pasta in this world, but <food>carbonara pasta</food> is one of the best ."
    }
]
  • Related