Python - Dictionaries

17.
Discuss the concept of nested dictionaries in Python.

In Python, a nested dictionary is a dictionary that contains another dictionary or dictionaries as values. This allows you to represent a hierarchical or structured data organization. Here's an example of nested dictionaries:

# Creating a nested dictionary
nested_dict = {
    'person1': {'name': 'John', 'age': 25, 'city': 'New York'},
    'person2': {'name': 'Alice', 'age': 30, 'city': 'San Francisco'}
}

# Accessing values in the nested dictionary
print("Name of person1:", nested_dict['person1']['name'])
print("Age of person2:", nested_dict['person2']['age'])

Output:

Name of person1: John
Age of person2: 30

In the example, the nested_dict contains two dictionaries ('person1' and 'person2') as values. You can access values in the nested dictionary using multiple keys. For example, to access the name of 'person1', you use nested_dict['person1']['name'].

Here's another example of nested dictionaries, where each person has information about their contact details:

# Creating a nested dictionary with contact details
contacts = {
    'person1': {
        'name': 'John',
        'age': 25,
        'address': {'city': 'New York', 'zipcode': '10001'},
        'email': 'john@example.com'
    },
    'person2': {
        'name': 'Alice',
        'age': 30,
        'address': {'city': 'San Francisco', 'zipcode': '94105'},
        'email': 'alice@example.com'
    }
}

# Accessing values in the nested dictionary
print("City of person1:", contacts['person1']['address']['city'])
print("Email of person2:", contacts['person2']['email'])

Output:

City of person1: New York
Email of person2: alice@example.com

In this example, the contacts dictionary has nested dictionaries for 'address'. You can access nested values by chaining the keys, such as contacts['person1']['address']['city'] to get the city of 'person1'.


18.
How do you create a shallow copy of a dictionary in Python?

To create a shallow copy of a dictionary in Python, you can use the copy() method. Here's an example:

# Original dictionary
original_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# Creating a shallow copy
shallow_copy_dict = original_dict.copy()

# Modifying the shallow copy
shallow_copy_dict['age'] = 30

# Printing original and shallow copy dictionaries
print("Original Dictionary:", original_dict)
print("Shallow Copy Dictionary:", shallow_copy_dict)

Output:

Original Dictionary: {'name': 'John', 'age': 25, 'city': 'New York'}
Shallow Copy Dictionary: {'name': 'John', 'age': 30, 'city': 'New York'}

In this example, the copy() method is used to create a shallow copy of the original_dict. Modifying the values in the shallow copy doesn't affect the original dictionary.


19.
What is the purpose of the defaultdict class in the collections module?

The defaultdict class in the collections module is a subclass of the built-in dict class. It overrides one method to provide a default value for a nonexistent key, which makes it particularly useful for creating dictionaries with default values.

Here's an example demonstrating the purpose of defaultdict:

from collections import defaultdict

# Creating a defaultdict with default value as 0
default_dict = defaultdict(int)

# Incrementing a non-existent key
default_dict['count'] += 1

# Accessing the defaultdict
print("Default Dictionary:", default_dict)

Output:

Default Dictionary: defaultdict(, {'count': 1})

In this example, the defaultdict is initialized with a default value of 0 (integer). When the key 'count' is accessed for the first time, it is automatically created with the default value, and the value is incremented by 1.


20.
Explain the difference between a dictionary and a set in Python.

In Python, both dictionaries and sets are unordered collections, but they serve different purposes and have distinct characteristics.

Difference between a dictionary and a set:

A dictionary is a collection of key-value pairs, where each key must be unique within the dictionary. It allows you to store and retrieve values based on their associated keys.

# Example of a dictionary
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

A set, on the other hand, is an unordered collection of unique elements. It doesn't have key-value pairs like a dictionary, and its primary purpose is to check for membership and perform set operations (union, intersection, etc.).

# Example of a set
my_set = {1, 2, 3, 4, 5}

Outputs:

Dictionary: {'name': 'John', 'age': 25, 'city': 'New York'}
Set: {1, 2, 3, 4, 5}

As shown in the examples, a dictionary uses key-value pairs, while a set consists of unique elements without associated values.