Python dict methods
Created By: chatGPT
get()
The get() method retrieves a value for a specified key. If the key is not found, it returns None
or a specified default value.
Example:
my_dict = {'name': 'John', 'age': 30}
print(my_dict.get('name')) # Output: John
print(my_dict.get('gender', 'Not specified')) # Output: Not specified
keys()
The keys() method returns a view object that displays a list of all the keys in the dictionary.
my_dict = {'name': 'John', 'age': 30}
print(my_dict.keys()) # Output: dict_keys(['name', 'age'])
values()
The values() method returns a view object that displays a list of all the values in the dictionary.
my_dict = {'name': 'John', 'age': 30}
print(my_dict.values()) # Output: dict_values(['John', 30])
items()
The items() method returns a view object that displays a list of the dictionary's key-value pairs as tuples.
my_dict = {'name': 'John', 'age': 30}
print(my_dict.items()) # Output: dict_items([('name', 'John'), ('age', 30)])
update()
The update() method updates the dictionary with elements from another dictionary or from an iterable of key-value pairs. If the key already exists, its value is updated.
my_dict = {'name': 'John', 'age': 30}
my_dict.update({'age': 31, 'city': 'New York'})
print(my_dict) # Output: {'name': 'John', 'age': 31, 'city': 'New York'}
pop()
The pop() method removes the specified key and returns the corresponding value. If the key is not found, a default value can be specified.
my_dict = {'name': 'John', 'age': 30}
age = my_dict.pop('age', 'Not Found')
print(age) # Output: 30
print(my_dict) # Output: {'name': 'John'}
clear()
The clear() method removes all items from the dictionary.
my_dict = {'name': 'John', 'age': 30}
my_dict.clear()
print(my_dict) # Output: {}
copy()
The copy() method returns a shallow copy of the dictionary.
my_dict = {'name': 'John', 'age': 30}
copied_dict = my_dict.copy()
print(copied_dict) # Output: {'name': 'John', 'age': 30}
print(copied_dict is my_dict) # Output: False
setdefault()
The setdefault() method returns the value of a specified key. If the key does not exist, it inserts the key with a specified default value.
my_dict = {'name': 'John'}
age = my_dict.setdefault('age', 30)
print(my_dict) # Output: {'name': 'John', 'age': 30}
print(age) # Output: 30