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

Question:

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].

Asked By: Hahaha2411

||

Answers:

Sort new_list with a lambda, with the key being the position the word is found in msg.

Code:

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)
        
new_list.sort(key=lambda x: msg.find(x))
        
        
print(new_list)

Output:

Enter

4 hi 3 very bad good
['hi', 'very bad', 'good']
Answered By: Ryan

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.

Answered By: Ryan Nygard
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.