Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I list specific words it finds in the order it finds them in

I’m creating a discord bot and was wondering how I could list out the words in order it finds them in?

item_dict = {
    "okay": ("Mythical", "50000"),
    "hello": ("Mythical", "17500"),
    "hi": ("Legendary", "14500"),
    "good": ("Legendary", "11600"),
    "very bad": ("Common", "1"),
    }

msg = input("Enter ")
new_list = []

for x in item_dict:
    if x in msg:
        new_list.append(x)
        
print(new_list)

If for example I enter 4 hi 3 very bad good, I would want it to check the string and check if it matches any of the items in the dictionary and make it print [hi, very bad, good] instead of how its ordered in the dictionary which would print out [hi, good, very bad].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Instead of looping through the dictionary loop through the message and then you can look for word matches when you hit a letter that matches the start of a key, like so:

item_dict = {
  "okay": ("Mythical", "50000"),
  "hello": ("Mythical", "17500"),
  "hi": ("Legendary", "14500"),
  "good": ("Legendary", "11600"),
  "very bad": ("Common", "1"),
}

msg = input("Enter ")
new_list = []

for index, letter in enumerate(msg):
  for key in item_dict.keys():
    if letter == key[0]:
      if msg[index:index+len(key)] == key:
        new_list.append(key)
        break



print(new_list)

This solution can also handle spaces in the dictionary keys, albeit at a higher computation cost.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading