How to get random replies for a input from json in python

Viewed 174

I have a json file containing some rules . This is an example:

[
  {
    "triggers": ["hello", "hey", "hi"],
    "replies": [
      {
        "reply": "Hey there"
      },
      {
        "reply": "Hola"
      },
      {
        "reply": "Hello World"
      }
    ]
  },
  {
    "triggers": ["who are you", "your name"],
    "replies": [
      {
        "reply": "some name"
      },
      {
        "reply": "lorem ipsum"
      }
    ]
  }
]

What I am trying to achive is if a user queries a text, let's say "hello" I want the script to search through the json file and see if the query exists in any trigger array. If it exists, then I want the script to pick a random reply from the replies array.

I can:

  • Change the json file as you want, as long as there is a list of triggers and a list of replies for each trigger.
  • Use loops. But remember that my json file is bigger than above so they shouldn't slow down my whole script.

I can't:

  • Use while loops or infinite loops. I have to process other data alongsides.

I've tried everything. Please help me if you could. Thank you for helping.

2 Answers

We can use random.choice(...) to pick a random element from a sequence. Notice that it will raise an error if sequence is empty. Assuming s is your list of dictionaries:

import random
def reply(greet):
    for e in s:
        if greet in e["triggers"]:
            return random.choice(e["replies"])["reply"]
    return ""

>>> reply("hey")
'Hey there'
>>> reply("hey")
'Hey there'
>>> reply("hey")
'Hello World'
>>> reply("hey")
'Hello World'
>>> reply("hey")
'Hola'
>>> reply("who are you")
'lorem ipsum'
>>> reply("who are you")
'some name'
>>> reply("not exist")
''

As you mentioned that you can modify the JSON and your concern is time too,

Consider this JSON,

{
    "query_reply_mapping": {
        "hello": "1",
        "hey": "1",
        "hi": "1",
        "who are you": "2"
    },
    "replies": {
        "1": ["Hey there", "Hola", "Hello World"],
        "2": ["some name", "lorem"]
    }

}

In the above JSON, query_reply_mapping is a mapping between the query and the possible reply array. The "1" and "2" here are the keys pointing to the possible replies for this query in the replies dictionary.

import random
json_data = {}
query="hello"
random.choice(json_data["replies"][json_data["query_reply_mapping"][query]])

This solution will be without loops and much faster than any other. Also, you can create a small script to modify your existing JSON to this that will be a one-time thing.

Related