What is setdefault() method in dictionary | How to use the setdefault() method of a dictionary.

Definition:

Refer below image while reading definition.

setdefaukt list python

This method returns the value of the specified key from the dictionary. Note that this method does not remove the item but it returns the copy of the item so the original item in the dictionary remains unchanged.

But this method also takes the 2nd argument which is optional. If the specified key is not present inside the dictionary, it will insert the item which is passed as argument and it will append it inside the dictionary changing the original dictionary and then returns that item.

Syntax:

X = dictionary.setdefault(‘key’, ‘value’)

Key = desired key which you want to search

Value = If key is not present insert this value with the key mentioned before and return this item as output. (Optional argument)

This method takes one compulsorily.

Working:

Python_Dictionary_setdefault()_Method

Setdefault_output

Code is here you can copy.

dictionary = {1: ‘Student’,
‘Name’: ‘Waqar Khan’,
‘Subjects’: ‘Computers’}

x = dictionary.setdefault(“Name”)
print(x)
y = dictionary.setdefault(‘University’,’MU’)
print(dictionary)
print(y)

Code:

  1. A dictionary with some random values is being taken
  2. setdefault() method is being applied with Name as argument
  3. return value is printed inside x
  4. Again setdefault() method is being applied but with unmatched key and 2nd argument which is value is passed
  5. The original dictionary is printed
  6. The returned value of setdefault() method is printed.

Output:

  1. Value of key Name is printed
  2. Original dictionary is printed with a new item since it was not present inside it.
  3. The appended item’s value is shown as output

Interview questions:

  • What will happen if you specify a key and which is not present inside the dictionary but also you do not specify any 2nd argument.

The method will not throw an error it simply returns None.

 

Waqar Khan

Hello, everyone, I am Waqar Khan. I have done my B.tech in Computer Science. I love to write about Computer Informational blogs. Before write I did proper research on it. Hope you like our blogs. Thank you.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *