Home > Net >  Delete key/value from a dictionary Json
Delete key/value from a dictionary Json

Time:04-11

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)

CodePudding user response:

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:

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)

Edit: I see that the indentation was edited just now

CodePudding user response:

if trova in data:
    del data[trova]

Calling dict.__del__ removes the key/value pair, so if your file is unchanged it's because the flow never enters the if statement.


Maybe it would work with

if trova in data.keys():

but I'm not sure if it makes any difference.

  • Related