Python Dictionary get() Method (with Examples)

Python Dictionary get() Method: In this tutorial, we will learn about the get() method of a dictionary with its usage, syntax, parameters, return type, and examples. By IncludeHelp Last updated : June 12, 2023

Python Dictionary get() Method

The get() is an inbuilt method of dict class that is used to get the value of an item based on the specified key. The method is called with this dictionary and returns the value if the given key exits; None, otherwise.

Syntax

The following is the syntax of get() method:

dictionary_name.fromkeys(keys, value)

Parameter(s):

The following are the parameter(s):

  • key – It represents the name of the key whose value to be returned.
  • value – It is an optional parameter, that is used to specify the value to be returned if item does not exist.

Return Value

The return type of this method is based on the element type, it returns the element on a specified key, if the key does not exist it returns "None", if we defined any value, it returns that value if the key does not exist.

Example 1: Use of Dictionary get() Method

# dictionary declaration
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "perc" : 98.5
}

# printing dictionary
print("data of student dictionary...")
print(student)

# printing the value of "roll_no"
print("roll_no is:", student.get('roll_no'))

# printing the value of "name"
print("name is:", student.get('name'))

# printing the value of "course"
print("course is:", student.get('course'))

# printing the value of "perc"
print("perc is:", student.get('perc'))

# trying to get item of the key which does not exist
print("address is:", student.get('address'))

# trying to get item of the key which does not exist
# and returning some value if key does not exist
print("address is:", student.get('address', "does not exist."))

Output

data of student dictionary...
{'perc': 98.5, 'course': 'B.Tech', 'name': 'Shivang', 'roll_no': 101}
roll_no is: 101
name is: Shivang
course is: B.Tech
perc is: 98.5
address is: None
address is: does not exist.

Example 2: Use of Dictionary get() Method

# dictionary declaration
x = {
    'key1' : 100,
    'key2' : 200,
    'key3' : 300
}

# getting value with defining value if key
# does not exist
print("key1 = ", x.get('key1', "Item does not exist."))
print("key2 = ", x.get('key2', "Item does not exist."))
print("key3 = ", x.get('key3', "Item does not exist."))
print("key4 = ", x.get('key4', "Item does not exist."))

Output

key1 =  100
key2 =  200
key3 =  300
key4 =  Item does not exist.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.