These bad boys are like hash maps in other languages but better because they have a time complexity of O(1) for both insertion and retrieval operations.
So Let’s get started with some examples! First, we can create a dictionary using curly braces or dictionary comprehensions:
# Creating a dictionary with curly braces
my_dict = {'name': 'John', 'age': 25} # creating a dictionary with key-value pairs using curly braces
print(my_dict) # printing the dictionary
# Output: {'name': 'John', 'age': 25}
# Creating a dictionary using comprehension
my_list = [1, 2, 3] # creating a list
square_dict = {x: x**2 for x in my_list} # creating a dictionary using dictionary comprehension, where the keys are the elements of the list and the values are the square of the elements
print(square_dict) # printing the dictionary
# Output: {1: 1, 2: 4, 3: 9}
Now that we have our dictionaries created, some of the operators and methods available to us. First up is the `[]` operator which allows us to access a value based on its key:
# Creating a dictionary with key-value pairs
my_dict = {'name': 'John', 'age': 25}
# Printing the value associated with the key 'name'
print(my_dict['name']) # Output: John
# The [] operator allows us to access a value in a dictionary based on its key.
# In this case, we are accessing the value associated with the key 'name' and printing it.
Next, we have the `[]=` operator which allows us to set or reset a value based on its key. This is useful for updating existing values in our dictionary:
# Setting Value using Key
my_dict = {'name': 'John', 'age': 25} # Creating a dictionary with key-value pairs
my_dict['age'] = 30 # Updating the value of 'age' key to 30
print(my_dict) # Printing the updated dictionary, {'name': 'John', 'age': 30}
Finally, we have the `del` statement which allows us to delete a key and its associated value from our dictionary. This is useful for removing unwanted data or cleaning up memory usage:
# Deleting Key-Value Pair using del Statement
# Create a dictionary with key-value pairs
my_dict = {'name': 'John', 'age': 30}
# Use the del statement to remove a key-value pair from the dictionary
del my_dict['age'] # Removing the age key and its associated value
# Print the updated dictionary
print(my_dict) # Output: {'name': 'John'}
# The del statement allows us to delete a key and its associated value from a dictionary.
# This is useful for removing unwanted data or cleaning up memory usage.
And that’s it! That’s all you need to know about dictionaries in Python. They may seem simple at first, but they can be incredibly powerful when used correctly. So go out there and start using them in your code today!