Python provides more adaptable data structures besides lists and tuples, such as dictionaries and sets. These structures are useful when storing and manipulating more complex data. Let’s get to know them!
Dictionaries
In Python, a dictionary is an unordered collection of elements, each containing a key-value pair. They can be changed and are surrounded by braces. Creating a Dictionary:
student = {"name": "John", "age": 21, "grade": "A"}
print(student) # Output: {'name': 'John', 'age': 21, 'grade': 'A'}
Accessing Dictionary Items:
print(student["name"]) # Output: 'John'
Modifying Dictionary Items:
student["grade"] = "A+"
print(student) # Output: {'name': 'John', 'age': 21, 'grade': 'A+'}
Sets
A set in Python is an unordered collection of unique items. They are mutable and enclosed within braces {}.
Creating a Set:
fruits = {"apple", "banana", "cherry"}
print(fruits) # Output: {'apple', 'banana', 'cherry'}
Note: Since sets are unordered, you might see the items displayed in a different order.Adding Items to a Set:
fruits. add("mango")
print(fruits) # Output: {'mango', 'apple', 'banana', 'cherry'}
Note: Adding an existing item doesn’t change the set as it only stores unique items.#### AssignmentIt’s now your chance to experiment with dictionaries and sets. Make a dictionary of your favorite book’s information (such as title, author, and year of release). Create a list of your favorite genres. Experiment with accessing and changing the elements in your dictionary and set.
Conclusion
Dictionaries and sets are important data structure capabilities in Python’s arsenal. They enable efficient data storage and manipulation, making them essential for many programming tasks. Continue to practice with other examples to achieve skill with these data structures!