Ticker

6/recent/ticker-posts

Dictionary Methods in Python

Dictionary Methods in Python

Introduction: 

Dictionaries in Python are a versatile and powerful data structure that stores key-value pairs. They allow quick and efficient data retrieval based on keys. This documentation provides an overview of some important dictionary methods in Python along with coding examples and explanations.

1. clear() Method
Description: The clear() method removes all items from a dictionary, making it empty.
Example:

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

2. get(key, default=None) Method
Description: The get() method returns the value for the specified key if it exists in the dictionary. If the key is not found, it returns the default value (None by default).
Example:

python
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
age = my_dict.get('age')
print(age) # Output: 30
country = my_dict.get('country', 'USA')
print(country) # Output: USA

3. items() Method
Description: The items() method returns a list of key-value pairs (tuples) as a view object of the dictionary.
Example:

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

4. keys() Method
Description: The keys() method returns a view object containing the keys of the dictionary.
Example:

python
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
keys_view = my_dict.keys()
print(keys_view) # Output: dict_keys(['name', 'age', 'city'])

5. values() Method
Description: The values() method returns a view object containing the values of the dictionary.
Example:

python
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
values_view = my_dict.values()
print(values_view) # Output: dict_values(['John', 30, 'New York'])

6. pop(key, default=None) Method
Description: The pop() method removes the item with the specified key from the dictionary and returns its value. If the key is not found, it returns the default value (None by default).
Example:

python
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
age = my_dict.pop('age')
print(age) # Output: 30
country = my_dict.pop('country', 'USA')
print(country) # Output: USA

Conclusion:
Dictionaries in Python offer a range of methods that facilitate efficient data manipulation and retrieval. By understanding and utilizing these methods, you can work effectively with dictionaries in your Python programs.

Post a Comment

0 Comments