Python Dictionary get() is a built-in function that returns the value for a specified key if present in the dictionary. If the key is not present, it returns None
by default.
get() Syntax
The syntax of the get()
method is:
dict.get(key,value)
get() Parameters
The get()
method takes two parameters.
- key– the key name of the item for which you want to return the value.
- value (Optional) – Value to be returned if the key is not found in the dictionary. If not provided, defaults to None.
get() Return Value
The get()
method returns
- the value of an item with the specified
key
if thekey
is present in the dictionary. None
if thekey
is not found in the dictionary, and the value argument is not specified.value
to be returned if thekey
is not found.
Example 1 – How to use the get() method in Dictionary
company = {"name": "Microsoft", "location": "Seattle"}
print("Company Name:", company.get("name"))
print("Company Location:", company.get("location"))
# In case of wrong key name without default value
print("Company Headquarters:", company.get("headquarters"))
# In case of wrong key name with default value
print("Company Headquarters:", company.get("headquarters","Not Found"))
Output
Company Name: Microsoft
Company Location: Seattle
Company Headquarters: None
Company Headquarters: Not Found
Example 2 – Difference between get() method and dict[key] to access elements
The get()
method will not raise any exception if the key
is not found, it either returns None
or a default value if provided.
On the other hand when we use dict[key]
if the key is not found KeyError
exception is raised.
company = {"name": "Microsoft", "location": "Seattle"}
# In case of wrong key name without default value
print("Company Headquarters:", company.get("headquarters"))
# In case of wrong key name with default value
print("Company Headquarters:", company.get("headquarters","Not Found"))
# when used dict[key]
print(company["headquarters"])
Output
Company Headquarters: None
Company Headquarters: Not Found
Traceback (most recent call last):
File "C:\Personal\IJS\Python_Samples\program.py", line 9, in <module>
print(company["headquarters"])
KeyError: 'headquarters'