我正在为我的机器人制作一个标记功能,我已经成功地制作了创建、使用和显示标记的命令。现在我纠结于如何根据给定的标签删除键和值。例如,!deletetag youtube
将从以下列表中删除youtube
标签:
{
"twitch": "https://www.twitch.tv/",
"youtube": "https://www.youtube.com/",
"ig": "https://www.instagram.com/",
"twitter": "https://twitter.com/"
}
我使用JSON文件来存储标签的原因是,机器人程序只会在<100个人,它不会包含超过30-40个标签。以下是我尝试过的:
@commands.command(name="deletetag",
help="Delete an existing tag.")
async def _deletetags(self, ctx, tag: str):
with open('tags.json') as output:
data = json.load(output)
for key in data:
del key[tag]
将我的评论作为答案,以便于参考。
# Remove key from dictionary
del data[tag]
# Serialize data and write back to file
with open('tags.json', 'w') as f:
json.dump(data, f)