In a simple Telegram bot with Telebot I have a dictionary in json format (parole.json). I’m trying a function that allows me to delete an entry (key value pair) from the dictionary and I used this code example found right on this forum:
import json
with open("parole.json", "r") as json_file:
Dizio = json.load(json_file)
@bot.message_handler(commands=['cut'])
def removeKey(message):
parola = extract_arg(message.text.lower())
res = Dizio.get(message.text.lower(), parola)
trova = str(parola)
with open("parole.json", "r") as f:
data = json.load(f)
if trova in data:
del data[trova]
with open("parole.json", "w") as f:
json.dump(data, f)
2
Answers
Have you read this question? It’s basically the same question and the answer is already given.
You need to iterate over the keys by using a for loop that checks if the
input == ['key']['value']
Also, your indenting is incorrect in your removekey(message) function:
Edit: I see that the indentation was edited just now
Calling
dict.__del__
removes thekey
/value
pair, so if your file is unchanged it’s because the flow never enters theif
statement.Maybe it would work with
but I’m not sure if it makes any difference.