-1

I have a Json file like this:

{
    "cat": "FILE3",
    "cat flag dog": "FILE5",
    "zebra tiger": "FILE9",
    "home cat": "FILE10",
    "tv snow": "FILE12",
}

In a Telegram bot, I would like to extract all the values that contain the word "cat" but if I search through the lambda function I get only this:

FILE3

while I would like to get all the results where the word cat appears:

FILE3

FILE5

FILE10

This is my code:

@bot.message_handler(func=lambda message: True)
def echo_message(message):
    with open("database.json", "r") as json_file:
            File = json.load(json_file)
        res = File.get(message.text.lower(), 'word not found')
        bot.send_message(message.chat.id, message.text)
        bot.send_message(message.chat.id, 'contain in:')
        bot.send_message(message.chat.id, res)

Thanks in advice.

1 Answers1

0

You need to search all keys in the dictionary. Build a list of values where the search criterion is found in a key. If the list is empty, return a constant string.

@bot.message_handler(func=lambda message: True)
def echo_message(message):
    with open("database.json", "r") as json_file:
        File = json.load(json_file)
        txt = message.text.lower()
        res = [v for k, v in File.items() if txt in k]
        bot.send_message(message.chat.id, message.text)
        bot.send_message(message.chat.id, 'contain in:')
        bot.send_message(message.chat.id, ', '.join(res) if res else 'word not found')

For the data shown, this would create:

FILE3, FILE5, FILE10
DarkKnight
  • 19,739
  • 3
  • 6
  • 22