Python

get() method in dictionary

Click for All Topics

get() method in dictionary - Python

  • This method is used to get the value of the specified key from a dictionary.
  • This method takes a required argument which is the key whose value you want to get and it also takes an optional argument default.
  • It will return None when specified key is not present in dictionary and default value is not specified.
  • The time complexity of this method is O(1).

 

Syntax –

dictionary.get(key, default=None)

 

Parameters –

  • key → key of dictionary whose value you want to retrieve
  • default(optional) → default value when key is not present, by default None
  • return → value of specified key

 

Example –

				
					student = {'name':'abc','rollno':1234,'year':4,'hobby':'scroll reels'}
print("Student details:",student)
print("Hobby of the student: ",student.get('hobby'))

# Output -
# Student details: {'name': 'abc', 'rollno': 1234, 'year': 4, 'hobby': 'scroll reels'}
# Hobby of the student:  scroll reels
				
			
  • In the above example, first we create a dictionary with student details and store it in student variable.
  • After creating student dictionary print the dictionary on the output screen.
  • Then using the .get() method we get the hobby of the student and then print on the output screen.

 

Example –

				
					# Print the math marks of the student 

marks={'hindi':90,'english':87,'physics':92,'chemistry':85}
math_marks=marks.get('math',"marks not found")
print("Math marks of the student:",math_marks)

# Output -
# Math marks of the student: marks not found
				
			

Example –

				
					# Print highest marks 
marks={'aman':78,'naman':92,'chaman':89,'suman':80}
highest_marks=0

for i in marks:
	current_marks=marks.get(i)
	if current_marks>highest_marks:
		highest_marks=current_marks

print("Highest marks :",highest_marks)

# Output -
# Highest marks : 92
				
			

Example –

				
					my_dict={'a':10,'b':20,'c':30,'d':40}
value=my_dict.get('e')
print("Value of e:",value)

# Output -
# Value of e: None