EN VI

how to print specific list of items from a dict in python?

2024-03-17 17:30:04
how to print specific list of items from a dict in python?

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)\Steam\steam.exe',
    'd' : r'C:\Users\User\AppData\Local\Discord\app-1.0.9036\Discord.exe',
    't' : r'C:\Users\User\AppData\Roaming\Telegram Desktop\Telegram.exe',
    'f' : r'C:\Program Files\Mozilla Firefox\firefox.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

Solution:

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)\Steam\steam.exe',
    'd' : r'C:\Users\User\AppData\Local\Discord\app-1.0.9036\Discord.exe',
    't' : r'C:\Users\User\AppData\Roaming\Telegram Desktop\Telegram.exe',
    'f' : r'C:\Program Files\Mozilla Firefox\firefox.exe',
}
    
for key in user_input:
    print(app_locate.get(key, f"Key {key} not found"))
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login