
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
get() method for dictionaries in Python
The get() method is part of standard python library to access the elements in a dictionary. Some times we may need to search for a key which is not present in the dictionary. In such case the accessing method by index is going to throw an error and halt the program. But we can use the get() method and handle the program without an error.
Syntax
Syntax: dict.get(key[, value]) The value field is optional.
Example
In the below example we create a dictionary called customer. It has address and distance as keys. We can print the keys without using get function and see the difference when we use the get function.
customer = {'Address': 'Hawai', 'Distance': 358} #printing using Index print(customer["Address"]) #printing using get print('Address: ', customer.get('Address')) print('Distance: ', customer.get('Distance')) # Key is absent in the list print('Amount: ', customer.get('Amount')) # A value is provided for a new key print('Amount: ', customer.get('Amount', 2050.0))
Output
Running the above code gives us the following result −
Hawai Address: Hawai Distance: 358 Amount: None Amount: 2050.0
So the new key is automatically accepted by the get method while we cannot do it using index.
- Related Articles
- Python Program to get all unique keys from a List of Dictionaries
- What are Ordered dictionaries in Python?
- Handling missing keys in Python dictionaries
- How are dictionaries implemented in Python?
- How to iterate over dictionaries using 'for' loops in Python?
- Python – Sort Dictionaries by Size
- How to create Ordered dictionaries in Python?
- Python - Difference in keys of two dictionaries
- Flatten given list of dictionaries in Python
- Passing Information using GET method in Python
- How do we compare two dictionaries in Python?
- How to perform Calculations with Dictionaries in Python?
- Python Program to compare elements in two dictionaries
- How to merge multiple Python dictionaries?
- Python program to merge to dictionaries.

Advertisements