Table of Contents
In this tutorial, we will learn about the Python Dictionary get() method with the help of examples.
The get()
method returns the value for the specified key if the key is in the dictionary.
Example
marks = {'Physics':67, 'Maths':87} print(marks.get('Physics')) # Output: 67
1. Syntax of Dictionary get()
The syntax of get()
is:
dict.get(key[, value])
2. get() Parameters
get()
method takes maximum of two parameters:
- key – key to be searched in the dictionary
- value (optional) – Value to be returned if the key is not found. The default value is
None
.
3. Return Value from get()
get()
method returns:
- the value for the specified key if key is in the dictionary.
None
if the key is not found and value is not specified.- value if the key is not found and value is specified.
4. Example 1: How does get() work for dictionaries?
person = {'name': 'Phill', 'age': 22} print('Name: ', person.get('name')) print('Age: ', person.get('age')) # value is not provided print('Salary: ', person.get('salary')) # value is provided print('Salary: ', person.get('salary', 0.0))
Output
Name: Phill Age: 22 Salary: None Salary: 0.0
5. Python get() method Vs dict[key] to Access Elements
get()
method returns a default value if the key
is missing.
However, if the key is not found when you use dict[key]
, KeyError
exception is raised.
person = {} # Using get() results in None print('Salary: ', person.get('salary')) # Using [] results in KeyError print(person['salary'])
Output
Salary: None Traceback (most recent call last): File "", line 7, in print(person['salary']) KeyError: 'salary'
Related posts:
Python Program to Access Index of a List Using for Loop
Python Program to Find Sum of Natural Numbers Using Recursion
Python List reverse()
Python Program to Convert Kilometers to Miles
Python Program to Safely Create a Nested Directory
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Program to Catch Multiple Exceptions in One Line
Python for Loop
Python sum()
Python String find()
Python Set discard()
Python bytearray()
Python Program to Convert Two Lists Into a Dictionary
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Set symmetric_difference_update()
How to get current date and time in Python?
Python String zfill()
Python String isprintable()
Python *args and **kwargs
Python Closures
Python Program to Check If a List is Empty
Python Program to Return Multiple Values From a Function
Python issubclass()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Program to Get the File Name From the File Path
Python Dictionary fromkeys()
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python Program to Print the Fibonacci sequence
Python Program to Convert Bytes to a String
Python String upper()
Python Inheritance
Python List copy()