Explain the set() and setdefault() methods in dictionary with suitable examples.

a) set() and setdefault() Methods in Dictionary

1. set() Function

In Python, set() is not a dictionary method but a built-in function used to create a set — an unordered collection of unique elements. It’s often used to eliminate duplicates from lists or other iterables.

Example:

numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers)

Output: {1, 2, 3, 4, 5}

2. setdefault() Method (Dictionary Method)

The setdefault() method returns the value of a key if it is present in the dictionary. If not, it inserts the key with a specified default value.

Syntax: dictionary.setdefault(key, default_value)

  • If the key exists: returns its value.
  • If the key does not exist: inserts key with default_value and returns default_value.

Example:

student = {'name': 'Rahul', 'age': 21}
# Key exists
print(student.setdefault('name', 'Unknown'))

# Key does not exist, so it's added
print(student.setdefault('branch', 'CSE'))

print(student)

Output:

b) Program to Swap the Case of a Given String

Problem Statement:

Write a Python program that takes a string input and returns a new string with all uppercase letters converted to lowercase and vice versa.

Program:





Example Output:

Leave a Reply

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