Python Dictionary get

The Python Dictionary get function is used to return the value at a given key position. If there is no user-given key inside a dictionary, the get() method returns None as the output. However, we can use the second argument to display the default value, if the given key is not present in a statement.

In this section, we discuss how to use this one, and the syntax behind this Python dictionary get function is:

diName.get(key, default_value)

Parameters: The get() function accepts two parameters.

  • key: Please specify the dictionary key to extract or get its corresponding value.
  • default_value: It is an optional argument. If we don’t use it, when the key is not present, the get() function returns None as the output. If we use this argument, instead of returning None, teh get() method returns this (Default_value) as the output.

Python Dictionary get Function Example

The dict get function returns the value associated with the specified user key. Please refer to the Dict article in Python. For more, refer to the dictionary methods article.

Python Dictionary get Function Example

In this program, we are using the second argument to display the default value. First, we are trying to access the non-exiting dict key. As you can see, it returns None because the key is not present.

However, you can use the second argument to specify the default value for non-existing values. Here, the last line of code is searched in the dictionary and returns the default word Mango.

myDi = {1: 'apple', 2: 'Banana' , 3: 'Orange', 4: 'Kiwi'}
print("Items: ", myDi)

print("\nKey 4  :  ",  myDi.get(4))
print("Key 5  :  ",  myDi.get(5))

print("\nKey 6  :  ",  myDi.get(6))
print("Key 6  :  ",  myDi.get(6, 'Mango'))
Items:  {1: 'apple', 2: 'Banana', 3: 'Orange', 4: 'Kiwi'}

Key 4  :   Kiwi
Key 5  :   None

Key 6  :   None
Key 6  :   Mango

Python dict get() function to get the nested dictionary value

Apart from the regular dicts, we can use the built-in get() function to return the nested dictionary value. However, based on the nested levels, we must us ethe get() function. 

In the following example, we declared a simple nested dictionary where there is a single person with a role and salary. Here, we used the company.get(“John”, {}).get(“salary”) to access the persons salalry.

company = {
"John": {"role": "Manager", "salary": 150000}
}

Salary = company.get("John", {}).get("salary")
print(Salary)
150000

In the following example, we used the typical nested dictionary example to extract its nested values using the get() function. We must call get() to access the dictionary items at each level. Here, there is no city key, so it returns none. However, we used the default value for the employee state setting to California (CA).

TIP: Use the dict.update() function to update the dictionary items.

company = {
"employees": {
"John": {"role": "Manager", "salary": 150000},
"Tracy": {"role": "Admin", "salary": 175000},
"Miller": {"role": "Developer", "salary": 120000},
}
}
admin_Salary = company.get("employees", {}).get("Tracy", {}).get("salary")
print(admin_Salary)

city = company.get("employees", {}).get("Miller", {}).get("city")
print(city)

state = company.get("employees", {}).get("John", {}).get("state", "CA")
print(state)
175000
None
CA

Python dictionary get if key exist otherwise get the default value if key is None

By default, the built-in get() method with a valid dictionary key (existing), this function returns the value associated with that key. If the user-specified key does not exist in the dictionary, it returns None as the output. However, if we use the second argument, we can get the default value if the specified key does not exist in the dictionary.

In the following Python dictionary get() function example,

  • user.get(“Age”) searches for the Age key inside the original dictionary. As the key is there, the get() function returns its associated value, i.e., 25.
  • user.get(“Income”): As there is no Income key inside the dict, the get() method returns None as the output.
  • user.get(“Income”, 120000): Here, we set the default Income value as 120000. It means, if the Income key is not present in the dictionary, the get() function returns 120000 (default value) instead of returning None.
user = {"Name": "Johny", "Age": 25, "Profession": "Engineer"}

user_age = user.get("Age")
print(user_age)

user_income = user.get("Income")
print(user_income)

new_income = user.get("Income", 120000)
print(new_income)
25
None
120000

What is the difference between dict.get() and dict[key] in Python?

We can use the built-in get() function or dict[key] to return the corresponding value for a given key. However, if the given key is not found in the original dictionary, the dict.get() function returns None whereas the dict[key] throws KeyError.

In the example below, the first two statements use the dict[key] and dict.get() to return the user name. As the key exists in the dictionary, both return the name as Johny.

Next, we used the dict.get() function to find the city name, because it does not exist in the dictionary, the get() function returns None, and the next line returns the default value “London”. On the other hand, when we use the dict[key] to find the city name (it does not exist in the dictionary), it returns KeyError.

user = {"Name": "Johny", "Age": 25}
print(user.get("Name"))
print(user["Name"])
print("------")
print(user.get("city"))
print(user.get("city", "London"))
print(user["city"])
Johny
Johny
------
None
London
KeyError: 'city'