Search code examples
pythondictionarykeyvaluepair

Getting Key Values from user input within python dict


I have hundreds of IP cameras that I have connected to an amazon ec2 instance, which performs NAT so the cameras use the Public IP of the instance and can be switched between cameras based on Port specified. I am trying to Write a simple python script that will return key values based on user input. for example, I want the user to be able to input "truck22" and based on that input be prompted for the correct port for that vehicle. Then I would like the script to open a webbrowser to the correct host and port. My Code looks like:

import webbrowser
import os
host = 192.168.1.1
trucks = {'truck22': ':1400', 'truck22 rear': ':1401', 'truck76': ':1412'}
for key in trucks.keys():
value = trucks.get(key)
choice = input("Select your item: ")
if choice in trucks:
webbrowser.open("http://" +host +value)
else:
print("invalid Truck number")

OUTPUT: webbrowser opens to 192.168.1.1:1400 The only issue am having is that it always returns the first key value of truck 22 which is port 1400, even if I enter another key name. Any Ideas?


Solution

  • You need to fetch the port from the dict using choice

    Ex:

    import webbrowser
    import os
    host = 192.168.1.1
    trucks = {'truck22': ':1400', 'truck22 rear': ':1401', 'truck76': ':1412'}
    
    choice = input("Select your item: ")
    if choice in trucks:
        webbrowser.open("http://" +host + ":" +trucks.get(choice))
    else:
        print("invalid Truck number")