+ 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.
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
+ 3
Bala Chinna that is exactly my solution
Manual inputđ
+ 3
Good hint Lothar
+ 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])
+ 2
print(dict[input()])
If your dictionary is dict
+ 1
Lothar thank you:)
+ 1
Oma Falk working superbly..... rocking now
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.
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.
0
Oma Falk thank you:)