But they do have keys and values! And thats what makes them so great for storing data in Python.
But did you know that dictionaries are more than just static storage devices? That’s right, my friend they can actually perform some pretty cool tricks with their methods! Let me show you a few of the most commonly used ones:
1) `get(key[, default])`
This method returns the value to which the specified key is mapped. If the key does not exist in the dictionary, it returns the optional second argument (default), if no default was given, then `KeyError` will be raised.
For example:
# This script demonstrates the use of the `get()` method in dictionaries.
# First, we create a dictionary called `my_dict` with two key-value pairs.
my_dict = {"name": "John", "age": 30}
# We use the `get()` method to retrieve the value associated with the key "name".
print(my_dict.get("name")) # Output: John
# We use the `get()` method to retrieve the value associated with the key "city".
# Since "city" does not exist in the dictionary, the method returns `None`.
print(my_dict.get("city")) # Output: None (no default given)
# We use the `get()` method to retrieve the value associated with the key "city".
# Since "city" does not exist in the dictionary, the method returns the default value "San Francisco".
print(my_dict.get("city", "San Francisco")) # Output: San Francisco
2) `items()`
This method returns a list of tuples representing each key-value pair in the dictionary as an iterator or a list, depending on whether it is called with brackets or parentheses.
For example:
# Create a dictionary with key-value pairs
my_dict = {"name": "John", "age": 30}
# Use the items() method to return a list of tuples representing each key-value pair in the dictionary
# The method can be called with brackets or parentheses, returning an iterator or a list respectively
# In this case, we use parentheses to return a list
# The output will be a list of tuples, with each tuple representing a key-value pair in the dictionary
print(list(my_dict.items())) # Output: [('name', 'John'), ('age', 30)]
3) `keys()`
This method returns a list of the dictionary’s keys as an iterator or a list, depending on whether it is called with brackets or parentheses.
For example:
# Creating a dictionary with key-value pairs
my_dict = {"name": "John", "age": 30}
# Using the keys() method to return a list of keys from the dictionary
# and converting it into a list using the list() function
# Output: ['name', 'age']
print(list(my_dict.keys()))
4) `values()`
This method returns a list of the dictionary’s values as an iterator or a list, depending on whether it is called with brackets or parentheses.
For example:
# Create a dictionary with key-value pairs
my_dict = {"name": "John", "age": 30}
# Use the values() method to return a list of the dictionary's values
# and convert it to a list using the list() function
# Output: ['John', 30]
print(list(my_dict.values()))
5) `popitem()`
This method removes and returns the last inserted key-value pair as a tuple (key, value). If the dictionary is empty, it raises KeyError.
For example:
# Create a dictionary with key-value pairs
my_dict = {"name": "John", "age": 30}
# Use the popitem() method to remove and return the last inserted key-value pair as a tuple
# If the dictionary is empty, it will raise a KeyError
# In this case, the last inserted key-value pair is ('age', 30)
# The popitem() method returns a tuple, so we can use the list() function to convert it into a list
# Then we can print the list to see the output
print(list(my_dict.popitem())) # Output: ['age', 30]
6) `setdefault(key[, default])`
This method returns the value to which the specified key is mapped in the dictionary. If the key does not exist in the dictionary, it sets the key with a given value and then returns that value. The optional second argument (default) specifies what value should be set if the key doesn’t already have one.
For example:
# This script creates a dictionary and uses the setdefault() method to add a new key-value pair if the key does not already exist.
my_dict = {"name": "John"} # Creates a dictionary with one key-value pair
print(list(my_dict.setdefault("age", 30))) # Uses setdefault() method to check if "age" key exists in dictionary. If not, it adds the key with a value of 30 and returns the value. The list() function is used to convert the returned value into a list. Output: [None, 30] (key 'age' was not in the dictionary)
print(list(my_dict)) # Converts the dictionary into a list and prints it. Output: ['name', 'age'] (new key 'age' was added to the dictionary)
7) `update([other])`
This method updates the dictionary with the key-value pairs from another dictionary or iterable. If there is a key that appears in both dictionaries, the corresponding value in the second dictionary will overwrite the one in the first dictionary.
For example:
# Define a dictionary with a key-value pair
my_dict = {"name": "John"}
# Define another dictionary with a key-value pair
other_dict = {"age": 30}
# Update the first dictionary with the key-value pairs from the second dictionary
my_dict.update(other_dict)
# Print the updated dictionary as a list
print(list(my_dict)) # Output: ['name', 'age']
# Explanation: The update() method adds the key-value pairs from the second dictionary to the first dictionary. If there is a key that appears in both dictionaries, the corresponding value in the second dictionary will overwrite the one in the first dictionary.
# Print the output of the update() method as a list
print(list(my_dict.update(other_dict))) # Output: [None, None]
# Explanation: The update() method does not return anything, so the output is a list of None values. The key 'age' was added to the dictionary, resulting in a list of two None values.
8) `clear()`
This method removes all items from the dictionary.
For example:
# Create a dictionary with key-value pairs
my_dict = {"name": "John", "age": 30}
# Use the clear() method to remove all items from the dictionary
my_dict.clear()
# Print the result of the clear() method, which should be an empty list
print(list(my_dict)) # Output: []
# Print the dictionary, which should also be empty
print(list(my_dict)) # Output: []
And that’s it, These are just a few of the most commonly used methods for dictionaries in Python. There are many more out there, but these should get you started on your journey to becoming a true Python master.