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 Remove Punctuations From a String
Python Dictionary setdefault()
Python frozenset()
Python Sets
Python String format_map()
Python hex()
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Program to Print all Prime Numbers in an Interval
Python List extend()
Python List pop()
Python String isprintable()
Python Program to Parse a String to a Float or Int
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python Matrices and NumPy Arrays
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python Program to Extract Extension From the File Name
Python Global Keyword
Python String isalnum()
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
How to Get Started With Python?
Python String count()
Python frozenset()
Python Program to Concatenate Two Lists
Python Inheritance
Python Program to Find All File with .txt Extension Present Inside a Directory
Python min()
Python Program to Convert String to Datetime
Python enumerate()
Python List insert()
Python Program to Print the Fibonacci sequence
Python String isspace()
Python String endswith()