替换字典列表中的项目
Replacing items in a 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 ."}, {...}, ...]
我必须在描述中用标签 <food> food </food>
突出显示食物,但我不知道如何在不使索引复杂化的情况下做到这一点。我最初的想法是:
for item in menu:
tag = item["food"]
if item["food"] in item["description"]:
i = tag.index()
tagging = "<food> " + tag + "</food>"
但后来我卡住了,因为我真的不知道如何更换物品。有什么建议吗?
IIUC,你想要的可以用replace
方法完成:
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))
输出:
[
{
"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 ."
}
]
我有以下词典列表:
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 ."}, {...}, ...]
我必须在描述中用标签 <food> food </food>
突出显示食物,但我不知道如何在不使索引复杂化的情况下做到这一点。我最初的想法是:
for item in menu:
tag = item["food"]
if item["food"] in item["description"]:
i = tag.index()
tagging = "<food> " + tag + "</food>"
但后来我卡住了,因为我真的不知道如何更换物品。有什么建议吗?
IIUC,你想要的可以用replace
方法完成:
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))
输出:
[
{
"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 ."
}
]