Home » Python

Python Dictionary setdefault() Method with Example

Python Dictionary setdefault() Method: Here, we are going to learn to get the value of an item with specified key and if key does not exist then set the key and value?
Submitted by IncludeHelp, on November 26, 2019

Dictionary setdefault() Method

setdefault() method is used to get the value of an item with the specified key and it sets an item (key, value) if the specified key does not exist in the dictionary.

Syntax:

    dictionary_name.setdefault(key, value)

Parameter(s):

  • key – It specifies the key name whose value to be returned to set.
  • value – It is an optional parameter, its default value is None, if the key does not exist, value becomes the value of the specified key.

Return value:

The return type of this method is the type of the value, it returns the value of specified keys.

Note: If value is not defined, it returns None.

Example:

# Python Dictionary setdefault() Method with Example

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

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

# getting value of 'roll_no'
x = student.setdefault('roll_no', 0)
print('roll_no: ', x)

# getting value of address key
# that does not exist, then function
# inserts given key & value
x = student.setdefault('address', 'New Delhi')
print('address: ', x)

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

# getting value of age key
# that does not exist, then function
# inserts given key & None
x = student.setdefault('age')
print('age: ', x)

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

Output

data of student dictionary...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5}
roll_no:  101
address:  New Delhi
data of student dictionary after setdefault()...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5, 'address': 'New Delhi'}
age:  None
data of student dictionary after setdefault()...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5, 'address': 'New Delhi', 'age': None}






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.