Dictionaries and Sets
Dictionaries are used to store key-value pairs, allowing for efficient lookup of values based on their associated keys. Sets, on the other hand, are collections of unique and unordered elements that can be used for various purposes such as membership testing, removing duplicates, and mathematical operations.
Creating and Modifying Dictionaries
A dictionary is a collection of key-value pairs. You can create an empty dictionary or a dictionary with values in it. Here are examples:
To add a key-value pair to a dictionary, simply assign a value to a new key, like this:
To modify an existing key-value pair, simply assign a new value to that key, like this:
Dictionary Methods
Dictionaries have several methods for manipulating and accessing data. Here are a few examples:
Set Operations and Methods
A set is an unordered collection of unique elements. You can create an empty set or a set with values in it. Here are examples:
To add an element to a set, use the add() method, like this:
To remove an element from a set, use the remove() method, like this:
Sets have several methods for manipulating and accessing data. Here are a few examples:
Combining Data Types
You can combine different data types to create complex data structures. Here’s an example:
In this example, we have a dictionary with a string key and values of different data types. The "hobbies" value is a list of strings, which is itself a data type. By combining data types like this, you can create powerful and flexible data structures for your programs.
