How to print dictionary value by getting user input? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

How to print dictionary value by getting user input?

Am trying to get user input and want to print key value. Not key. Can anyone help me on this.

12th Apr 2020, 9:19 AM
Bala Chinna
Bala Chinna - avatar
10 Answers
+ 6
I would not recommend accessing a dict by using dict[<keyname>]. If the key is not in the dict, the programm crashes and gives a key error. Better to use dict.get(<keyname>) like this: (basic code sample from Felix - thanks!) # Creating a Dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} # accessing a element using key print("Accessing a element using key:") #print(Dict[2]) # this line creates a Key error nad crashes print(Dict.get(2, 'No such Key found!')) # this line outputs message <No such Key found!>, but no crash
12th Apr 2020, 1:12 PM
Lothar
Lothar - avatar
+ 3
Bala Chinna that is exactly my solution Manual input💃
12th Apr 2020, 12:12 PM
Oma Falk
Oma Falk - avatar
+ 3
Good hint Lothar
12th Apr 2020, 1:30 PM
Oma Falk
Oma Falk - avatar
+ 2
# Creating a Dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} # accessing a element using key print("Accessing a element using key:") print(Dict['name']) # accessing a element using key print("Accessing a element using key:") print(Dict[1])
12th Apr 2020, 9:38 AM
Felix Gautsch 🍕
Felix Gautsch 🍕 - avatar
+ 2
print(dict[input()]) If your dictionary is dict
12th Apr 2020, 9:46 AM
Oma Falk
Oma Falk - avatar
+ 1
Lothar thank you:)
12th Apr 2020, 1:58 PM
Bala Chinna
Bala Chinna - avatar
+ 1
Oma Falk working superbly..... rocking now
12th Apr 2020, 4:04 PM
Bala Chinna
Bala Chinna - avatar
0
Felix Gautsch🍕 Hi Felix, thanks for this. But, what exactly I need is user need to enter the input as 1 or 2 or 3 manually and this need to print accordingly. Thanks again.
12th Apr 2020, 9:51 AM
Bala Chinna
Bala Chinna - avatar
0
Oma Falk hi, thanks... My query is user need to enter the input as 1 or 2 or 3 manually and this need to print accordingly. Thanks again.
12th Apr 2020, 9:53 AM
Bala Chinna
Bala Chinna - avatar
0
Oma Falk thank you:)
12th Apr 2020, 1:57 PM
Bala Chinna
Bala Chinna - avatar