Change language

Get () method for dictionaries in Python

| |

dic = { " A " : 1 , "B" : 2 }

print (dic [ "A" ])

print (dic [ "C" ])

The problem that comes up here is that the 3rd line of code returns a key error:

 Traceback (most recent call last): File "", line 3, in print (dic ["C"]) KeyError: ’C’ 

The get () method is used, to avoid such situations. This method returns the value for the given key, if present in the dictionary. If not, then it will return None (if get () is used with only one argument).

Syntax :

Dict.get (key, by default = No)


dic = { "A" : 1 , "B" : 2 }

print (dic.get ( "A" ))

print (dic.get ( "C" ))

print (dic.get ( " C " , " Not Found! " ))


 1 None Not Found! 

This article is contributing to Mayank Rawata If you love Python.Engineering and would like to contribute, you can also write an article using or mail article [email protected] See your article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.


Learn programming in R: courses


Best Python online courses for 2022


Best laptop for Fortnite


Best laptop for Excel


Best laptop for Solidworks


Best laptop for Roblox


Best computer for crypto mining


Best laptop for Sims 4


Latest questions


psycopg2: insert multiple rows with one query

12 answers


How to convert Nonetype to int or string?

12 answers


How to specify multiple return types using type-hints

12 answers


Javascript Error: IPython is not defined in JupyterLab

12 answers



Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method