Ticker

20/recent/ticker-posts

Modifying Dictionaries and Sets in Python

In the previous blog, we learned how to create and access dictionaries and sets in Python. In this blog, we will learn how to modify these data structures.


Modifying Dictionaries

Dictionaries are mutable in Python, which means that we can modify the contents of a dictionary after it has been created. To add a new key-value pair to a dictionary, we can simply assign a value to a new key. Here is an example:

my_dict = {"apple": 2, "banana": 3, "orange": 4}

my_dict["pear"] = 5

print(my_dict)  # Output: {"apple": 2, "banana": 3, "orange": 4, "pear": 5}

In this example, we have added a new key-value pair to the my_dict dictionary by assigning a value of 5 to the key "pear".

We can also modify the value of an existing key by assigning a new value to the key. Here is an example:


my_dict = {"apple": 2, "banana": 3, "orange": 4}

my_dict["banana"] = 5

print(my_dict)  # Output: {"apple": 2, "banana": 5, "orange": 4}

In this example, we have modified the value of the "banana" key in the my_dict dictionary by assigning a new value of 5.

To remove a key-value pair from a dictionary, we can use the del keyword. Here is an example:


my_dict = {"apple": 2, "banana": 3, "orange": 4}

del my_dict["banana"]

print(my_dict)  # Output: {"apple": 2, "orange": 4}

In this example, we have removed the "banana" key-value pair from the my_dict dictionary using the del keyword.


Modifying Sets

Sets are also mutable in Python, which means that we can modify the contents of a set after it has been created. To add an element to a set, we can use the add() method. Here is an example:


my_set = {1, 2, 3, 4, 5}

my_set.add(6)

print(my_set)  # Output: {1, 2, 3, 4, 5, 6}

In this example, we have added element 6 to the my_set set using the add() method.

To remove an element from a set, we can use the remove() or discard() method. The remove() method raises a KeyError if the element is not found in the set, while the discard() method does not raise an exception. Here is an example:


my_set = {1, 2, 3, 4, 5}

my_set.remove(3)

print(my_set)  # Output: {1, 2, 4, 5}



my_set.discard(6)

print(my_set)  # Output: {1, 2, 4, 5}

In this example, we have removed element 3 from the my_set set using the remove() method. We have also attempted to remove element 6 from the set using the discard() method, but since 6 is not in the set, nothing happens.


Conclusion

In this blog, we have learned how to modify dictionaries and sets in Python

Post a Comment

0 Comments