Python Forum
User Input to Choose from Dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
User Input to Choose from Dictionary
#1
Hello,

I'm looking to post a list of databases from a dictionary, then from the user input choose which database they want to connect.

import pprint, os

db_list = {
    1: {'name': 'TEST11C'},
    2: {'name': 'TEST12C'},
}
print("Databases:")
for x, y in db_list.items():
    print(x, y)

while True:
    print("Select a database: ")
    name = int(input())

    if name in db_list.keys():
        print("You have chosen: " + name)
    else:
        print('You chosen wrong!')
The user will select a database value based on the key integers of [1,2]. If they select out of that range they'll receive an error. If they select within the range it will take the value of the database.

Any help is appreciated.

Thanks,
Frank
Reply
#2
Doesn't what you already have do that?
Reply
#3
No. When I enter a '1' for 'TEST11C' or '2' for the other one, I receive 'You chosen wrong!' when I should I receive the first part of the IF condition.

Databases:
1 {'name': 'TEST11C'}
2 {'name': 'TEST12C'}
Select a database:
1
You chosen wrong!
Select a database:

That was after I removed 'int' from input.
Reply
#4
Your code works for me if I correct the TypeError
Error:
Databases: (1, {'name': 'TEST11C'}) (2, {'name': 'TEST12C'}) Select a database: 1 Traceback (most recent call last): print("You have chosen: " + name) TypeError: cannot concatenate 'str' and 'int' objects >>>
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
Got it, thx for that!

Here's my fix:

while True:
    print("Select a database: ")
    name = int(input())

    if name in db_list.keys():
        name = int(name)
        print("You have chosen: ", name, db_list[name])
    else:
        print('You chosen wrong!')
One other thing, how do I display only the database name and not the dictionary entry?

Output:

Select a database:
1
You have chosen: 1 {'name': 'TEST11C'}

Desired output:

Select a database:
1
You have chosen: TEST11C
Reply
#6
Finished code:

db_list = {
    1: {'name': 'TEST11C'},
    2: {'name': 'TEST12C'},
}
print("Databases:")
for x, y in db_list.items():
    print(x, ':', db_list[x]['name'])

while True:
    print("\nSelect a database:")
    name = int(input())

    if x in db_list.keys():
        x = int(x)
        print("\nYou have chosen {0}".format(db_list[x]['name']))
    else:
        print('\nYou chosen wrong!')
Thanks for the help!
Reply
#7
A few comments:
  • db_list - this variable name implies that it's a list, while in fact you have dict. You may decide to switch to list (see my next comment)
  • dict is not ordered. In python3.6 the order of elements is preserved, but according to docs this is considered implementation detail and should not be relied upon. In other words the order in which you print dict items may be different from what you expect.
  • line#13 - I expect you want to use name, not x. As it is now x is the last item from previous for loop, thus will always be present in db_list.keys(). Here keys() is not necessary, in always checks in dict.keys() by default
  • line #15 - again you want to use name (i.e. the user input from line#11, not x

I just saw your other thread where you do use list, not dict
https://python-forum.io/Thread-Display-L...User-Input
I will not merge both threads as the other one is much older, but I post this link for completeness.
db_list = ['TEST11C', 'TEST12C']
print("Available Databases:")
for i, db_name in enumerate(db_list, start=1):
    print ('{}. {}'.format(i, db_name))
 
while True:
    try:
        selected = int(input('Select a database (1-{}): '.format(i)))
        db_name = db_list[selected-1]
        print('You have selected {}'.format(db_name))
        break
    except (ValueError, IndexError):
        print('This is not a valid selection. Please enter number between 1 and {}!'.format(i))
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#8
All your points taken into consideration. I'm unsure which direction to go in order to present the user a list of values. I started off with a list but was having trouble presenting the values. With a dictionary, it seems much simpler. I'm a beginner to programming so all the feedback you provided is much appreciated.

I updated my code with the following, per your advice:

databases = {
    1: {'name': 'TEST11C'},
    2: {'name': 'TEST12C'},
}

# Print databases listed in dictionary
print("Databases:")
for x, y in databases.items():
    print(x, ':', databases[x]['name'])

while True:
    print("\nSelect a database:")
    d_val = int(input())

    if d_val in databases.keys():
        d_val = int(d_val)
        print("\nYou have chosen {0}".format(databases[d_val]['name']))
    else:
        print('\nYou chosen wrong!')
Reply
#9
I updated my post #7 with an example
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#10
Awesome, got it! Thanks a lot for the example and advice.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  WHILE LOOP NOT RETURNING USER INPUT AFTER ZerroDivisionError! HELP! ayodele_martins1 7 1,053 Oct-01-2023, 07:36 PM
Last Post: ayodele_martins1
  restrict user input to numerical values MCL169 2 907 Apr-08-2023, 05:40 PM
Last Post: MCL169
  user input values into list of lists tauros73 3 1,064 Dec-29-2022, 05:54 PM
Last Post: deanhystad
Information How to take url in telegram bot user input and put it as an argument in a function? askfriends 0 1,073 Dec-25-2022, 03:00 PM
Last Post: askfriends
Question Take user input and split files using 7z in python askfriends 2 1,081 Dec-11-2022, 07:39 PM
Last Post: snippsat
Sad how to validate user input from database johnconar 3 1,910 Sep-11-2022, 12:36 PM
Last Post: ndc85430
  How to split the input taken from user into a single character? mHosseinDS86 3 1,166 Aug-17-2022, 12:43 PM
Last Post: Pedroski55
  Use pexpect to send user input alisha17 0 1,888 May-10-2022, 02:44 AM
Last Post: alisha17
  WHILE Loop - constant variables NOT working with user input boundaries C0D3R 4 1,475 Apr-05-2022, 06:18 AM
Last Post: C0D3R
  Mac os choose file name howard687 1 1,858 Jan-05-2022, 06:54 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020