skip to Main Content

i am trying to print only the "s" & "t" values from the dictionary of app_locate using the input_list list of [‘s’ , ‘t’] but i get the whole list of app_locate instead.

user_input = 'st'

input_list = list(user_input)


app_locate = {
    's' : r'C:Program Files (x86)Steamsteam.exe',
    'd' : r'C:UsersUserAppDataLocalDiscordapp-1.0.9036Discord.exe',
    't' : r'C:UsersUserAppDataRoamingTelegram DesktopTelegram.exe',
    'f' : r'C:Program FilesMozilla Firefoxfirefox.exe',
}
    
for input_list in app_locate:
    print(app_locate[input_list])

im not sure what im doing wrong here.

im rather new to python, sorry!

thank you for your help

2

Answers


  1. You do not need to convert user input to a list as you can just iterate over the string as follows:

    user_input = 'st'
    
    app_locate = {
        's' : r'C:Program Files (x86)Steamsteam.exe',
        'd' : r'C:UsersUserAppDataLocalDiscordapp-1.0.9036Discord.exe',
        't' : r'C:UsersUserAppDataRoamingTelegram DesktopTelegram.exe',
        'f' : r'C:Program FilesMozilla Firefoxfirefox.exe',
    }
        
    for key in user_input:
        print(app_locate.get(key, f"Key {key} not found"))
    
    Login or Signup to reply.
  2. It seems like you’re iterating over the keys of the app_locate dictionary instead of iterating over the items in the input_list. You need to iterate over the input_list and check if each character is in the app_locate dictionary. Here’s the corrected version of your code:

    user_input = 'st'
    
    input_list = list(user_input)
    
    app_locate = {
        's' : r'C:Program Files (x86)Steamsteam.exe',
        'd' : r'C:UsersUserAppDataLocalDiscordapp-1.0.9036Discord.exe',
        't' : r'C:UsersUserAppDataRoamingTelegram DesktopTelegram.exe',
        'f' : r'C:Program FilesMozilla Firefoxfirefox.exe',
    }
        
    for char in input_list:
        if char in app_locate:
            print(app_locate[char])
    

    This code will iterate over each character in input_list and check if it exists as a key in the app_locate dictionary. If it does, it will print the corresponding value. This way, only the values associated with ‘s’ and ‘t’ will be printed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search