08 Python Dictionary Methods
08 Python Dictionary Methods
clear()
Removes all the elements from a dictionary.
Syntax – dictionary.clear()
Ex:
student = {
"name": "Krishna",
"age": 25,
"place": "Vrindavan"
}
student.clear()
print(student)
copy()
Returns a copy of the specified dictionary.
Syntax – dictionary.copy()
Ex:
god = {
"name": "Krishna",
"age": 25,
"place": "Vrindavan"
}
x = god.copy()
print(x)
fromkeys()
Returns a dictionary with the specified keys
and the specified value.
Ex:
x = ('ssc', 'inter', 'btech')
y = 'Anantapur'
student_dict = dict.fromkeys(x, y)
print(student_dict)
Syntax – dict.fromkeys(keys, value)
Parameters:
keys – Required – iterable
An iterable specifying the keys of the
new dictionary.
Parameters:
key – Required – key
The key name.
Syntax – dictionary.items()
Parameters: No
student = {
"name": "Hari",
"age":25,
"email": "hari@gmail.com"
}
x = student.items()
print(x)
student["age"] = 30
print(x)
keys()
Returns a view object.
Syntax – dictionary.keys()
Parameters: No
pop()
Updates the dictionary by removing the specified item
from.
Parameters:
key – Required – key
The key name.
Syntax – dictionary.popitem()
Parameters: No
setdefault()
Parameters:
key – Required – key
The key name.
Syntax:dictionary.update(dictionary)
Parameters:
dictionary – Required – dictionary
A dictionary with key and value.
values()
Returns a view object.
Syntax – dictionary.values()
Parameters: No