Computer >> Computer tutorials >  >> Programming >> Python

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.