Assignment - 2
Assignment - 2
Assignment - 2
Shubham Kumar
Assignment -2
1. What is a list in python?
Ans - A list in Python is a collection of items that are ordered and changeable. We can think of it
like a container that can hold multiple pieces of data, such as numbers, strings, or even other lists.
Here are some key features of lists:
• Ordered: The items in a list have a specific order, and each item can be accessed by its
position, called an index. The first item has an index of 0, the second item has an index of 1,
and so on.
Ex - fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
print(fruits[2]) # Output: cherry
• Changeable: You can add, remove, or change items in a list after it has been created.
fruits[0] = “blueberry”
print(fruits) # Output : [‘blueberry’, ‘banana’, ‘cherry’]
• Allows duplicates: A list can have multiple items with the same value.
fruits[1] = “blueberry”
print(fruits) # Output: [‘blueberry’, ‘blueberry’, ‘cherry’]
2. How do you create a list in python?
Ans - Creating a list in Python is simple. We just need to use square brackets [] and separate the
items with commas. Here are a few examples:
• fruits = ["apple", "banana", "cherry"]
• numbers = [1, 2, 3, 4, 5]
• mixed_list = [1, "apple", 3.14, True]
3. How do you access elements in a list?
Ans - To access elements in a list, we use index, which is a number representing their position in the
list. Indexing starts from 0, so the first element is at index 0, the second element is at index 1, and
so on. You can also use negative indexing to access elements from the end of the list, with -1 being
the last element, -2 being the second last, etc.
• Accessing Elements by Index :
1. num = [31, 73, 98, 19, 50]
print(num[2]) # Output: 98.
• Accessing Slices of the List print(num[2:4]) # Output: [98, 19]
4. How can you slice a list in Python?
Ans - n Python, slicing typically applies to sequences like strings, lists, and tuples. If we want to
"slice" a number, you first need to convert it into a string. Once it's a string, you can slice it just like
any other string. After slicing, if you need the result as a number, you can convert it back to an
integer or float.
Steps to Slice a number :
• Convert the number to a string.
• Slice the string.
• Optionally, convert the sliced string back to a number.
num = 123456
num_str = str(num)
sliced_str = num_str[:3]
sliced_num = int(sliced_str)
print(sliced_num) # Output: 123
nums.insert(1, 26)
print(nums) # Output : [81, 26, 23, 44, 19, 34, 72, 67]
6. How do you remove an element from a list?
Ans – Removing elements from a list in Python using several methods, including remove(),
pop(), and del. Each method has a specific use case depending on how and which element you
want to remove.
• Using `remove()` :
• The remove() method removes the first occurrence of a specified value from the list.
original_list = [1, 2, 3, 4]
copied_list = original_list[:]
print(copied_list) # Output: [1, 2, 3, 4]
• Using the `list()` constructor :
• The list() constructor can be used to create a shallow copy of the list.
original_list = [1, 2, 3, 4]
copied_list = list(original_list)
print(copied_list) # Output: [1, 2, 3, 4]
• Using the `copy` module for deep copy :
• If you need a deep copy (i.e., a copy where all nested objects are also copied), you can use
the deepcopy() function from the copy module. This creates a new list and recursively
copies all objects contained in the original list.
import copy
original_list = [[1, 2], [3, 4]]
deep_copied_list = copy.deepcopy(original_list)
print(deep_copied_list) # Output: [[1, 2], [3, 4]]
13. How do you check if an element is in a list?
Ans - You can check if an element is in a list using the in operator. This operator returns True if
the element is present in the list and False otherwise.
• Using a Dictionary :
• In Python 3.7 and later, dictionaries maintain insertion order. You can use a dictionary to
remove duplicates while preserving order.
original_list = [1, 2, 2, 3, 4, 4, 5]
# Remove duplicates while preserving order using dictionary keys
unique_list = list(dict.fromkeys(original_list))
print(unique_list) # Output: [1, 2, 3, 4, 5]
• Using a loop :
• You can also manually check for duplicates using a loop and a temporary list to preserve
order.
original_list = [1, 2, 2, 3, 4, 4, 5]
# Remove duplicates while preserving order using a loop
unique_list = []
for item in original_list:
if item not in unique_list:
unique_list.append(item)
print(unique_list) # Output: [1, 2, 3, 4, 5]
15. How do you reverse a list?
Ans - You can reverse a list in Python using several methods. Here are the most common ways:
• Using the `reverse()` method :
• The reverse() method reverses the list in place, meaning it modifies the original list and
does not return a new list.
my_list = [1, 2, 3, 4, 5]
# Reversing the list in place
my_list.reverse()
print(my_list) # Output: [5, 4, 3, 2, 1]
my_list = [1, 2, 3, 4, 5]
# Iterate over the list using a for loop
for item in my_list:
print(item)
2. Using a `while` loop
• You can also use a while loop with an index to iterate over a list.
my_list = [1, 2, 3, 4, 5]
index = 0
# Iterate using a while loop
while index < len(my_list):
print(my_list[index])
index += 1
3. Using a List comprehensions
• List comprehensions are a concise way to create lists based on existing lists. They can also
be used for iteration.
my_list = [1, 2, 3, 4, 5]
# List comprehension to iterate and transform elements
squared = [x ** 2 for x in my_list]
print(squared) # Output: [1, 4, 9, 16, 25]
4. Using `enumerate()`
• The enumerate() function adds a counter to the list, which is useful if you need both the
index and the item during iteration.
my_list = ['a', 'b', 'c']
# Iterate with index and value
for index, value in enumerate(my_list):
print(f"Index: {index}, Value: {value}")
5. Using `map()`
• The map() function applies a function to each item in the list and returns an iterator. You
can convert this iterator to a list if needed.
my_list = [1, 2, 3, 4, 5]
# Function to be applied
def square(x):
return x ** 2
# Iterate using map()
squared = list(map(square, my_list))
print(squared) # Output: [1, 4, 9, 16, 25]
6. Using `filter()`
• The filter() function allows you to iterate and filter items based on a condition.
my_list = [1, 2, 3, 4, 5]
# Function to determine if an item is even
def is_even(x):
return x % 2 == 0
# Filter using filter()
evens = list(filter(is_even, my_list))
print(evens) # Output: [2, 4]
19. How can you count the occurrences of an element in a list?
Ans - To count the occurrences of an element in a list, you can use several methods in Python. Here
are the most common ways:
1. Using the `count()` method
• The count() method is a built-in list method that returns the number of occurrences of a
specified item.
my_list = [1, 2, 2, 3, 4, 2]
# Count occurrences of the number 2
count = my_list.count(2)
print(count) # Output: 3
2. Using a loop
• You can manually count occurrences by iterating through the list and maintaining a counter.
my_list = [1, 2, 2, 3, 4, 2]
element = 2
count = 0
# Count occurrences using a loop
for item in my_list:
if item == element:
count += 1
print(count) # Output: 3
3. Using a dictionary
• If you need to count occurrences of multiple elements, you can use a dictionary to store the
counts.
my_list = [1, 2, 2, 3, 4, 2]
count_dict = {}
# Count occurrences using a dictionary
for item in my_list:
if item in count_dict:
count_dict[item] += 1
else:
count_dict[item] = 1
print(count_dict) # Output: {1: 1, 2: 3, 3: 1, 4: 1}
4. Using the `collections.Counter`
• The Counter class from the collections module provides a convenient way to count
occurrences of elements in a list.
from collections import Counter
my_list = [1, 2, 2, 3, 4, 2]
count_dict = Counter(my_list)
print(count_dict) # Output: Counter({2: 3, 1: 1, 3: 1, 4: 1})
print(count_dict[2]) # Output: 3
Each method is useful depending on your needs—whether you're counting a single element or
multiple elements, or if you need a simple or more detailed count.
20. How do you convert a list to a string and vice versa?
Ans - Converting between lists and strings is a common task in Python. Here's how you can do it:
Converting a List to a String
1. Using `join()` method
• The join() method is commonly used to convert a list of strings into a single string, with
a specified delimiter between elements.
my_list = ['apple', 'banana', 'cherry']
# Convert list to string with comma separator
my_string = ', '.join(my_list)
print(my_string) # Output: "apple, banana, cherry"
TUPLES
21. What is a tuple in Python?
Ans - A tuple in Python is an ordered, immutable collection of elements. Tuples are similar to lists,
but unlike lists, the elements of a tuple cannot be changed once they are assigned. This immutability
makes tuples useful for situations where a collection of items should not be modified.
Key characterisitcs of tuples:
1. Ordered: The elements in a tuple have a defined order, and that order will not change.
2. Immutable: Once a tuple is created, its elements cannot be changed, added, or removed.
3. Heterogeneous: Tuples can contain elements of different data types.
4. Indexed: Elements in a tuple can be accessed using indexing, similar to lists.
5. Allow Duplicates: Tuples can contain duplicate elements.
22. How do you create a tuple?
Ans - Tuples can be created by placing a comma-separated sequence of elements within parentheses
().
# Creating a tuple
my_tuple = (1, 2, 3)
print(my_tuple) # Output: (1, 2, 3)
my_tuple = (1, 2, 3)
single_element_tuple = (1,)
3. Performace Generally have a smaller May take up more memory and
memory footprint and can be be slightly slower in some
faster to iterate through due to operations due to their
their immutability. mutability and additional
features.
4. Use cases Used when the collection of Used when the collection of
items should not change. items may change. Suitable for
Commonly used for fixed collections where elements will
collections of items, such as be added, removed, or
coordinates, RGB color values, modified.
or database records.
shopping_list = ['eggs', 'milk',
coordinates = (10, 20) 'bread']
color = (255, 255, 255) shopping_list.append('butter')
5. Methods Limited methods. Only More versatile with various
supports basic operations like methods for manipulation,
count() and index(). including append(),
6. Example my_tuple = (1, 2, 3, 1) my_list = [1, 2, 3]
my_list.append(4)
print(my_tuple.count(1))
# Output: 2 print(my_list)
# Output: [1, 2, 3, 4]
print(my_tuple.index(2))
# Output: 1
my_tuple = (1, 2, 3, 4, 5)
# Access elements from index 1 to 3 (exclusive)
print(my_tuple[1:4]) # Output: (2, 3, 4)
3. Using a loop: You can use a loop to iterate over the elements of a tuple.
my_tuple = (1, 2, 3, 4, 5)
# Iterate through the tuple and print each element
for element in my_tuple:
print(element)
4. Using `enumerator()`: The enumerate() function adds a counter to the tuple, which is
useful if you need both the index and the element during iteration.
my_tuple = ('a', 'b', 'c')
# Iterate through the tuple with index
for index, value in enumerate(my_tuple):
print(f"Index: {index}, Value: {value}")
5. Nested Tuples: If you have a tuple that contains other tuples (nested tuples), you can access
elements in the nested tuples using multiple indices.
nested_tuple = (1, (2, 3), (4, 5, 6))
# Access the second element of the nested tuple
print(nested_tuple[1]) # Output: (2, 3)
# Access the second element within the nested tuple
print(nested_tuple[1][1]) # Output: 3
25. How can you slice a tuple?
Ans - Slicing a tuple in Python is similar to slicing a list. You can extract a portion of a tuple by
specifying a range of indices. The slice notation follows the pattern start:stop:step, where:
my_tuple = (1, 2, 3, 4, 5)
# Slice from index 1 to 3 (excluding 4)
print(my_tuple[1:4]) # Output: (2, 3, 4)
if element in my_tuple:
print(f"{element} is in the tuple.")
else:
print(f"{element} is not in the tuple.")
In this example, 3 is in the tuple, so the output will be `3 is in the tuple`.
x, y = get_coordinates()
32. What are some common methods for tuples?
Ans - Tuples in Python have a limited set of methods compared to lists. The common methods
available for tuples are:
1. count(value): Returns the number of occurrences of value in the tuple.
my_tuple = (1, 2, 2, 3, 3, 3)
count_of_twos = my_tuple.count(2)
print(count_of_twos) # Output: 2
2. index(value, start=0, end=len(tuple)): Returns the index of the first
occurrence of value within the specified range. Raises a ValueError if the value is not
found.
my_tuple = (1, 2, 3, 4, 2)
index_of_two = my_tuple.index(2)
print(index_of_two) # Output: 1
33. How do you iterate over a tuple?
Ans - To iterate over a tuple in Python, you can use a for loop. Here’s a basic example:
my_tuple = (1, 2, 3, 4, 5)
for item in my_tuple:
print(item)
In this example, the for loop iterates over each element in my_tuple, printing each item in
sequence. This approach is straightforward and efficient for accessing and processing each element
of a tuple.
34. How can you count the occurrences of an element in a tuple?
Ans - To count the occurrences of an element in a tuple, you can use the count() method. Here’s
how you do it:
my_tuple = (1, 2, 3, 4, 2, 2, 5)
index_of_30_in_range = my_tuple.index(30, 0, 4)
print(index_of_30_in_range) # Output: 2
Here, the search is limited to the elements between indices 0 and 4 (excluding 4).
SETS
36. What is a set in Python?
Ans - In Python, a set is a collection of unique, unordered elements. Unlike lists or tuples, sets do
not allow duplicate items, and the order of elements is not preserved. Here are some key
characteristics and uses of sets:
1. Unique elements: Sets automatically remove duplicate values. If you try to add a duplicate
element, it will be ignored.
2. Unordered: Sets do not maintain the order of elements. The order in which elements are
added is not necessarily the order in which they are iterated over.
3. Mutable: Sets are mutable, meaning you can add or remove elements after the set is
created.
4. Set Operations: Sets support operations like union, intersection, difference, and symmetric
difference.
5. Set comprehensions: Similar to list comprehensions, you can create sets using set
comprehensions.
37. How do you create a set?
Ans - You can create a set in Python using curly braces {} or the set() constructor. Here are a
few ways to create sets:
1. Using curly braces:
my_set = {1, 2, 3, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5}
2. Using `set()` constructor:
my_list = [1, 2, 2, 3, 4]
my_set = set(my_list)
print(my_set) # Output: {1, 2, 3, 4}
3. Creating an Empty set:
empty_set = set()
print(empty_set) # Output: set()
38. How do you add an element to a set?
Ans - To add an element to a set in Python, you can use the add() method. Here’s how you can do
it:
my_set = {1, 2, 3}
my_set = {1, 2, 3, 4}
my_set.remove(3)
my_set = {1, 2, 3, 4}
removed_element = my_set.pop()
print(removed_element) # Output: (an arbitrary element from the set)
print(my_set) # The set without the removed element.
40. How do you check if an element is in a set?
Ans - To check if an element is in a set in Python, you use the in keyword. Here’s how you can do
it:
my_set = {1, 2, 3, 4, 5}
The in keyword checks for membership efficiently and is the standard way to determine if an
element is present in a set.
41. What are the advantages of using sets?
Ans - Using sets in Python offers several advantages:
1. Uniqueness: Sets automatically eliminate duplicate elements, which is useful when you
need to store a collection of unique items without manually checking for duplicates.
2. Fast Membership training: Sets provide O(1) average time complexity for membership
tests (checking if an item is in the set), which is faster than lists where the time complexity
is O(n).
3. Set operations: Sets support mathematical set operations like union, intersection,
difference, and symmetric difference, making it easy to perform these operations on
collections of items.
4. Mutable but Hashable: While sets themselves are mutable (you can add or remove
elements), the elements inside a set must be hashable and immutable (e.g., numbers, strings,
tuples).
5. Set comprehensions: Similar to list comprehensions, you can use set comprehensions to
create sets in a concise and readable manner.
42. How do you find the union of two sets?
Ans - To find the union of two sets in Python, you can use the | operator or the union() method.
Both approaches produce a new set containing all unique elements from both sets.
• Using the | Operator:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}
Both methods will give you a set that includes all elements from set1 and set2, with duplicates
automatically removed.
43. How do you find the intersection of two sets?
Ans - To find the intersection of two sets in Python, you can use the & operator or the
intersection() method. Both approaches produce a new set containing only the elements that
are present in both sets.
• Using the & Operator:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {3}
Both methods will give you a set that includes only the elements that are present in both set1 and
set2.
44. How do you find the difference between two sets?
Ans - To find the difference between two sets in Python, you can use the - operator or the
difference() method. The difference of two sets produces a new set containing elements that
are present in the first set but not in the second set.
• Using the – Operator:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2}
Both methods will give you a set containing elements that are in set1 but not in set2.
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # Output: {1, 2, 5, 6}
Both methods will give you a set containing elements that are present in either set1 or set2, but
not in both.
46. How do you iterate over a set?
Ans - To iterate over a set in Python, you use a for loop. Here’s how you can do it:
my_set = {1, 2, 3, 4, 5}
my_set = {1, 2, 3}
my_set.clear()
print(my_set) # Output: set()
• copy(): Returns a shallow copy of the set.
my_set = {1, 2, 3}
copy_set = my_set.copy()
print(copy_set) # Output: {1, 2, 3}
• union(*sets): Returns a new set with elements from the set and all other sets.
set1 = {1, 2}
set2 = {2, 3}
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3}
These methods allow you to perform a variety of operations on sets, making it easier to manage
collections of unique items.
49. How do you clear all elements from a set?
Ans - To clear all elements from a set in Python, you use the clear() method. This method
removes all elements from the set, leaving it empty.
my_set = {1, 2, 3, 4, 5}
Dictionaries
51. What is a dictionary in Python?
Ans - A dictionary in Python is a collection of key-value pairs. Each key is unique, and it's used to
access its associated value. Think of it like a real-life dictionary where you look up a word (the key)
to find its definition (the value).
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
52. How do you create a dictionary?
Ans - You can create a dictionary in Python using curly braces {} with key-value pairs separated by
commas. Here's a step-by-step guide:
my_dict = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
53. How do you access values in a dictionary?
Ans - To access values in a dictionary, you use the key associated with the value you want to
retrieve. Here's how you can do it:
• Using Square Brackets:
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
value = my_dict["name"] # Accesses the value associated with the key "name"
print(value) # Output: Alice
• Using the get() Method:
value = my_dict.get("age") # Accesses the value associated with the key "age"
print(value) # Output: 30
print(my_dict)
• Using the update() Method:
my_dict.update({
"country": "USA",
"occupation": "Engineer"
})
print(my_dict)
55. How do you remove a key-value pair from a dictionary?
Ans - To remove a key-value pair from a dictionary, you have several options:
• Using the del Statement: The del statement removes a key-value pair from a dictionary
by specifying the key.
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
del my_dict["city"] # Removes the key "city" and its associated value
print(my_dict)
• Using the pop() Method: The pop() method removes the key-value pair and returns the
value associated with the key. You can also provide a default value to return if the key is not
found.
value = my_dict.pop("age") # Removes the key "age" and returns its value
print(value) # Output: 30
my_dict.clear()
print(my_dict) # Output: {}
56. How do you check if a key is in a dictionary?
Ans - To check if a key exists in a dictionary, you can use several methods:
• Using the in Operator: This is the most common and straightforward way to check if a
key is present in a dictionary.
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
if "age" in my_dict:
print("Key 'age' exists in the dictionary.")
if "country" not in my_dict:
print("Key 'country' does not exist in the dictionary.")
• Using the get() Method: While get() is typically used to retrieve a value, it can also be
used to check if a key exists by seeing if it returns None (or a default value if provided).
if my_dict.get("country") is None:
print("Key 'country' does not exist in the dictionary.")
• Using the keys() Method: You can also use the keys() method to get a view of the
dictionary's keys and check for membership.
if "age" in my_dict.keys():
print("Key 'age' exists in the dictionary.")
However, this is less efficient than using the in operator directly on the dictionary.
numbers = [1, 2, 3, 4, 5]
squares = {num: num ** 2 for num in numbers}
print(squares)
59. How do you find the length of a dictionary?
Ans - To find the length of a dictionary, which is the number of key-value pairs it contains, you can
use the len() function.
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
length = len(my_dict)
print(length) # Output : 3
In this example, len(my_dict) returns 3 because there are three key-value pairs in the
dictionary.
60. How do you merge two dictionaries?
Ans - To merge two dictionaries in Python, you can use several methods depending on the version
of Python you're using and the desired behavior.
• Using the update() Method (Python 3.5+)
• The update() method updates the dictionary with elements from another dictionary. If
there are duplicate keys, the values from the second dictionary will overwrite those in the
first dictionary.
dict1 = {
"name": "Alice",
"age": 30
}
dict2 = {
"city": "New York",
"country": "USA"
}
dict1.update(dict2)
print(dict1)
• Using Dictionary Unpacking (Python 3.5+)
• You can use the ** unpacking operator to merge dictionaries. This method creates a new
dictionary with the combined keys and values.
• dict1 = {
• "name": "Alice",
• "age": 30
• }
•
• dict2 = {
• "city": "New York",
• "country": "USA"
• }
•
• merged_dict = {**dict1, **dict2}
•
• print(merged_dict)
• Using the | Operator (Python 3.9+)
• In Python 3.9 and later, you can use the | operator to merge dictionaries. This creates a new
dictionary with the combined keys and values.
dict1 = {
"name": "Alice",
"age": 30
}
dict2 = {
"city": "New York",
"country": "USA"
}
print(merged_dict)
Each method has its use cases, but all are effective for merging dictionaries in Python.
61. How do you get a list of all keys in a dictionary?
Ans - To get a list of all keys in a dictionary, you can use the keys() method, which returns a view
of the dictionary’s keys. You can then convert this view to a list if needed.
Here's how you can do it:
1. Using keys() Method and Converting to a List:
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
keys_list = list(my_dict.keys())
print(keys_list)
2. Directly Using the keys() Method:
values_list = list(my_dict.values())
print(values_list) # Output : ['Alice', 30, 'New York']
2. Directly Using the values() Method:
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
items_list = list(my_dict.items())
print(items_list)
#Output : [('name', 'Alice'), ('age', 30), ('city', 'New York')]
2. Directly Using the items() Method:
my_dict.clear()
print(my_dict) # Output: {}
After calling my_dict.clear(), the dictionary my_dict will be empty.
The copy() method creates a shallow copy of the dictionary. This means that it copies the
dictionary itself but not the objects that the dictionary values reference. Changes to mutable objects
inside the dictionary will affect both the original and copied dictionaries.
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
copied_dict = my_dict.copy()
print(copied_dict) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
2. Shallow Copy Using Dictionary Unpacking
In Python 3.5 and later, you can use dictionary unpacking to create a shallow copy:
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
copied_dict = {**my_dict}
If the dictionary contains nested mutable objects and you need to ensure that these objects are also
copied (not just referenced), you should use a deep copy. The copy module provides a
deepcopy() function for this purpose.
import copy
my_dict = {
"name": "Alice",
"age": 30,
"address": {
"city": "New York",
"zip": "10001"
}
}
deep_copied_dict = copy.deepcopy(my_dict)
print(deep_copied_dict)
Each method has its use case depending on whether you need a shallow or deep copy.
To update the value of an existing key in a dictionary, you can directly assign a new value to that
key. If the key already exists, its value will be updated; if the key does not exist, it will be added
with the new value.
1. Direct Assignment:
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print(my_dict)
2. Using the update() Method:
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# Update the value of an existing key and add new keys if needed
my_dict.update({"age": 31, "city": "Los Angeles"})
print(my_dict)
Both methods will effectively update the value of an existing key in the dictionary. Use direct
assignment for a single key, and update() for updating multiple keys or merging dictionaries.
print(my_dict)
• Using the update() Method: The update() method can also be used to update the
value of one or more existing keys. If a key exists, its value is updated; if not, the key-value
pair is added.
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print(my_dict)
Both methods allow you to efficiently update values in a dictionary.
68. How do you handle missing keys in a dictionary?
Ans - Handling missing keys in a dictionary can be done in several ways depending on what you
want to achieve. Here are some common methods:
1. Using get() Method: The get() method allows you to provide a default value if the key
is not found. If the key exists, it returns its value; if not, it returns the specified default value
(or None if no default is provided).
my_dict = {
"name": "Alice",
"age": 30
}
# Handle missing key with a default value
value = my_dict.get("city", "Not Found")
print(value) # Output: Not Found
2. Using in Operator: Before accessing a key, you can check if it exists using the in
operator.
my_dict = {
"name": "Alice",
"age": 30
}
if "city" in my_dict:
print(my_dict["city"])
else:
print("Key 'city' is missing.")
Each of these methods provides a way to manage missing keys based on your specific needs.
69. What is the difference between `get()` and `[]` when accessing dictionary values?
Ans - The get() method and square bracket notation ([]) are both used to access values in a
dictionary, but they behave differently when dealing with missing keys:
Difference get() []
Behavior The get() method returns the The square bracket notation
value associated with the accesses the value associated
specified key if it exists. If the with the specified key. If the
key does not exist, it returns key does not exist, it raises a
None (or a specified default KeyError.
value if provided).
Syntax value = my_dict.get(key, value = my_dict[key]
default_value)
Use case get() is useful when you Square bracket notation is used
want to handle missing keys when you are certain that the
gracefully without raising an key exists in the dictionary or
error. It allows you to provide a when you want to handle the
default value if the key is not situation using exception
found. handling.
Use get() when you want to avoid exceptions and handle missing keys with default values. Use
square bracket notation when you want to ensure the key exists and are ready to handle a potential
KeyError.
70. How do you create a dictionary with default values?
Ans - To create a dictionary with default values, you can use several methods depending on your
needs:
1. Using `defaultdict` from the `collections` Module: `defaultdict` is a
subclass of the `built-in dict` class. It overrides the default behavior to provide a default
value for missing keys, using a factory function.
from collections import defaultdict
print(my_dict["a"]) # Output: 1
print(my_dict["b"]) # Output: 2
print(my_dict["c"]) # Output: 0 (default value)
2. Using `fromkeys()` Method: The `fromkeys()` method creates a new dictionary
with specified keys and assigns a default value to all keys.
keys = ["a", "b", "c"]
default_value = 0
# Create a dictionary with keys from the list and all values set to default_value
my_dict = dict.fromkeys(keys, default_value)