Dictionary Methods
-
This lesson covers commonly used dictionary methods and their practical applications in Python.
Dictionary Methods
A dictionary method is a built-in function used to perform operations on dictionaries.
get() Method
Safely gets the value of a key without error if key doesn't exist.
student = {"name": "Ravi", "age": 20}
print(student.get("name"))
print(student.get("marks", "Not Found"))
keys() Method
Returns all keys from the dictionary.
student = {"name": "Ravi", "age": 20}
print(student.keys())
values() Method
Returns all values from the dictionary.
student = {"name": "Ravi", "age": 20}
print(student.values())
items() Method
Returns key-value pairs.
student = {"name": "Ravi", "age": 20}
print(student.items())
update() Method
Updates existing data or adds new key-value pairs.
student = {"name": "Ravi", "age": 20}
student.update({"age": 21, "marks": 85})
print(student)
pop() Method
Removes a specific key.
student = {"name": "Ravi", "age": 20}
student.pop("age")
print(student)
popitem() Method
Removes the last inserted item.
student = {"name": "Ravi", "age": 20, "marks": 90}
student.popitem()
print(student)
clear() Method
Removes all items.
student = {"name": "Ravi", "age": 20}
student.clear()
print(student)
copy() Method
Creates a copy of dictionary.
student = {"name": "Ravi", "age": 20}
new_student = student.copy()
print(new_student)