Python - Dictionaries

9.
How can you remove a key-value pair from a dictionary in Python?

In Python, you can remove a key-value pair from a dictionary using the pop() method. This method takes a key as an argument and removes the corresponding key-value pair from the dictionary. Here is an example:

# Original dictionary
student_info = {"Name": "John", "Age": 25, "City": "New York"}

# Removing a key-value pair using pop()
removed_value = student_info.pop("Age")

# Displaying the updated dictionary and the removed value
print("Updated Dictionary:", student_info)
print("Removed Value:", removed_value)

Output:

Updated Dictionary: {'Name': 'John', 'City': 'New York'}
Removed Value: 25

In this example, the pop() method is used to remove the key-value pair with the key "Age" from the student_info dictionary. The updated dictionary and the removed value are then displayed.


10.
Discuss the concept of dictionary comprehension in Python.

Dictionary comprehension is a concise way to create dictionaries in Python using a single line of code. It is similar to list comprehension but produces dictionaries. Here's an example to illustrate the concept:

# Using dictionary comprehension to create a dictionary
squared_values = {x: x**2 for x in range(1, 6)}

# Displaying the resulting dictionary
print(squared_values)

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

In this example, the dictionary comprehension is used to create a dictionary where the keys are numbers from 1 to 5, and the values are the squares of the corresponding keys. The resulting dictionary {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} is displayed.


11.
What happens if you try to access a key that doesn't exist in a dictionary?

When attempting to access a key that doesn't exist in a dictionary, a KeyError will be raised. It's important to handle such situations to prevent program crashes. Here's an example:

# Creating a dictionary
sample_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# Accessing an existing key
print("Name:", sample_dict['name'])

# Attempting to access a non-existent key
try:
    print("Gender:", sample_dict['gender'])
except KeyError as e:
    print(f"KeyError: {e}")

Output:

Name: John
KeyError: 'gender'

In this example, the program successfully accesses the existing key 'name' and prints its value. However, when attempting to access the non-existent key 'gender', a KeyError is caught in the except block, and an appropriate error message is displayed.


12.
How can you check if a key is present in a dictionary?

You can check if a key is present in a dictionary using the in keyword or the get() method. Here's an example:

# Creating a dictionary
sample_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# Using the 'in' keyword
key_to_check = 'age'
if key_to_check in sample_dict:
    print(f"{key_to_check} is present in the dictionary.")
else:
    print(f"{key_to_check} is not present in the dictionary.")

# Using the 'get()' method
key_to_check = 'gender'
value = sample_dict.get(key_to_check, 'Key not found')
print(f"{key_to_check}: {value}")

Output:

age is present in the dictionary.
gender: Key not found

In this example, the program checks whether the key 'age' is present in the dictionary using the in keyword. It also checks for the key 'gender' using the get() method, providing a default value ('Key not found') if the key is not present.