Python Tutorial: Dictionary Methods ๐ŸŽฏ

beginner
20 min

Python Tutorial: Dictionary Methods ๐ŸŽฏ

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! ๐Ÿ 

What is a Dictionary in Python? ๐Ÿ“

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:

python
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.

Dictionary Methods ๐Ÿ’ก

Python dictionaries have several built-in methods to perform various operations. Here are some commonly used ones:

1. dict.keys() ๐Ÿ”‘

This method returns all the keys present in the dictionary as a list.

python
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'city'])

2. dict.values() ๐Ÿ“‹

This method returns all the values present in the dictionary as a list.

python
print(my_dict.values()) # Output: ['John', 30, 'New York']

3. dict.items() ๐Ÿ—ƒ๏ธ

This method returns all the key-value pairs in the dictionary as a list of tuples.

python
print(my_dict.items()) # Output: [('name', 'John'), ('age', 30), ('city', 'New York')]

4. dict.get(key, default) ๐ŸŒ

This method returns the value for the given key if it exists, otherwise it returns the specified default value.

python
print(my_dict.get('city', 'Default City')) # Output: New York print(my_dict.get('gender', 'Default Gender')) # Output: Default Gender

5. dict.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.

python
other_dict = {'job': 'Engineer'} my_dict.update(other_dict) print(my_dict) # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'job': 'Engineer'}

Quiz Time! ๐ŸŽฒ

Quick Quiz
Question 1 of 1

What does the `dict.get(key, default)` method do in Python?

Practice Time! ๐Ÿงช

Now, try using these methods with a more complex dictionary and see how they work.

python
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! ๐ŸŽ‰