Welcome to our comprehensive guide on Python Dictionary Methods! In this lesson, we'll explore various methods that can be used with dictionaries, making them more powerful and practical. Let's dive in! ๐
Before we delve into the methods, let's understand what a dictionary is. A dictionary is a collection of key-value pairs. Here's a simple example:
my_dict = {
'name': 'John',
'age': 30,
'city': 'New York'
}In this example, 'name', 'age', and 'city' are keys, and 'John', 30, and 'New York' are their corresponding values.
Python dictionaries have several built-in methods to perform various operations. Here are some commonly used ones:
dict.keys() ๐This method returns all the keys present in the dictionary as a list.
print(my_dict.keys())
# Output: dict_keys(['name', 'age', 'city'])dict.values() ๐This method returns all the values present in the dictionary as a list.
print(my_dict.values())
# Output: ['John', 30, 'New York']dict.items() ๐๏ธThis method returns all the key-value pairs in the dictionary as a list of tuples.
print(my_dict.items())
# Output: [('name', 'John'), ('age', 30), ('city', 'New York')]dict.get(key, default) ๐This method returns the value for the given key if it exists, otherwise it returns the specified default value.
print(my_dict.get('city', 'Default City'))
# Output: New York
print(my_dict.get('gender', 'Default Gender'))
# Output: Default Genderdict.update(other_dict) ๐This method updates the dictionary with another dictionary. All the key-value pairs from the other_dict are merged into the original dictionary.
other_dict = {'job': 'Engineer'}
my_dict.update(other_dict)
print(my_dict)
# Output: {'name': 'John', 'age': 30, 'city': 'New York', 'job': 'Engineer'}What does the `dict.get(key, default)` method do in Python?
Now, try using these methods with a more complex dictionary and see how they work.
users = {
'alice': {'name': 'Alice', 'age': 25, 'city': 'Seattle'},
'bob': {'name': 'Bob', 'age': 30, 'city': 'Chicago'},
'charlie': {'name': 'Charlie', 'age': 22, 'city': 'New York'}
}
print(users.keys())
print(users.values())
print(users.items())
print(users['alice'].get('city', 'Default City'))
print(users['david'].get('name', 'Default Name')) # KeyError: 'david'
users['dave'] = {'name': 'Dave', 'age': 35, 'city': 'Los Angeles'}
print(users)Remember, the key for a dictionary can be any immutable type like string or integer, but the value can be any Python object.
Happy coding! ๐