Lesson 33 of 70 – Python Dictionary Methods
47%

Python Dictionary Methods

Python provides several built-in methods for working with dictionaries. These methods help you access, add, update, remove, and copy dictionary data.

Note: Dictionary methods are used to work efficiently with key-value pairs.
1. Common Dictionary Methods
Method Purpose
get() Returns the value of a specified key
keys() Returns all dictionary keys
values() Returns all dictionary values
items() Returns key-value pairs
update() Adds or updates dictionary items
pop() Removes a specified key and returns its value
popitem() Removes and returns the last inserted key-value pair
clear() Removes all dictionary items
copy() Creates a copy of the dictionary
setdefault() Returns a value and optionally inserts a default value
2. get() Method

The get() method returns the value associated with a specified key.

student = {
    "name": "Amit",
    "age": 20
}

print(student.get("name"))
Output:
Amit
3. get() for a Missing Key

If the key does not exist, get() returns None by default.

student = {
    "name": "Amit"
}

print(student.get("age"))
Output:
None
4. get() with a Default Value

You can provide a default value that will be returned when the key does not exist.

student = {
    "name": "Amit"
}

print(student.get("age", 18))
Output:
18
5. keys() Method

The keys() method returns a view containing all dictionary keys.

student = {
    "name": "Amit",
    "age": 20,
    "course": "Python"
}

print(student.keys())
Output:
dict_keys(['name', 'age', 'course'])
6. Looping Through keys()
student = {
    "name": "Amit",
    "age": 20,
    "course": "Python"
}

for key in student.keys():
    print(key)
Output:
name
age
course
7. values() Method

The values() method returns a view containing all dictionary values.

student = {
    "name": "Amit",
    "age": 20,
    "course": "Python"
}

print(student.values())
Output:
dict_values(['Amit', 20, 'Python'])
8. Looping Through values()
student = {
    "name": "Amit",
    "age": 20,
    "course": "Python"
}

for value in student.values():
    print(value)
Output:
Amit
20
Python
9. items() Method

The items() method returns a view containing all key-value pairs.

student = {
    "name": "Amit",
    "age": 20
}

print(student.items())
Output:
dict_items([('name', 'Amit'), ('age', 20)])
10. Looping Through items()
student = {
    "name": "Amit",
    "age": 20
}

for key, value in student.items():
    print(key, ":", value)
Output:
name : Amit
age : 20
11. update() Method

The update() method adds new key-value pairs or updates existing keys.

student = {
    "name": "Amit",
    "age": 20
}

student.update({"course": "Python"})

print(student)
Output:
{'name': 'Amit', 'age': 20, 'course': 'Python'}
12. update() Existing Value

If the key already exists, update() changes its value.

student = {
    "name": "Amit",
    "age": 20
}

student.update({"age": 21})

print(student)
Output:
{'name': 'Amit', 'age': 21}
13. pop() Method

The pop() method removes the specified key and returns its associated value.

student = {
    "name": "Amit",
    "age": 20,
    "course": "Python"
}

age = student.pop("age")

print(age)
print(student)
Output:
20
{'name': 'Amit', 'course': 'Python'}
14. pop() with Default Value

You can provide a default value to pop(). This avoids a KeyError when the specified key is missing.

student = {
    "name": "Amit"
}

result = student.pop("age", "Not Found")

print(result)
Output:
Not Found
15. popitem() Method

The popitem() method removes and returns the last inserted key-value pair.

student = {
    "name": "Amit",
    "age": 20,
    "course": "Python"
}

item = student.popitem()

print(item)
print(student)
Output:
('course', 'Python')
{'name': 'Amit', 'age': 20}
16. popitem() on an Empty Dictionary

Calling popitem() on an empty dictionary raises a KeyError.

student = {}

student.popitem()
Result:
KeyError: 'popitem(): dictionary is empty'
17. clear() Method

The clear() method removes all key-value pairs from a dictionary.

student = {
    "name": "Amit",
    "age": 20,
    "course": "Python"
}

student.clear()

print(student)
Output:
{}
18. copy() Method

The copy() method creates a shallow copy of a dictionary.

student = {
    "name": "Amit",
    "age": 20
}

new_student = student.copy()

print(new_student)
Output:
{'name': 'Amit', 'age': 20}
19. Changing a Dictionary Copy

Changing a separate dictionary created with copy() does not change the top-level contents of the original dictionary.

student = {
    "name": "Amit",
    "age": 20
}

new_student = student.copy()

new_student["age"] = 21

print("Original:", student)
print("Copy:", new_student)
Output:
Original: {'name': 'Amit', 'age': 20}
Copy: {'name': 'Amit', 'age': 21}
20. setdefault() Method

The setdefault() method returns the value of a key. If the key does not exist, it inserts the key with a specified default value.

student = {
    "name": "Amit"
}

age = student.setdefault("age", 20)

print(age)
print(student)
Output:
20
{'name': 'Amit', 'age': 20}
21. setdefault() with Existing Key

If the key already exists, setdefault() returns its existing value and does not replace it with the default value.

student = {
    "name": "Amit",
    "age": 20
}

result = student.setdefault("age", 25)

print(result)
print(student)
Output:
20
{'name': 'Amit', 'age': 20}
22. fromkeys() Method

The fromkeys() method creates a new dictionary using the specified keys and an optional common value.

keys = ("name", "age", "course")

student = dict.fromkeys(keys)

print(student)
Output:
{'name': None, 'age': None, 'course': None}
23. fromkeys() with a Common Value
keys = ("name", "age", "course")

student = dict.fromkeys(keys, "Not Available")

print(student)
Output:
{'name': 'Not Available', 'age': 'Not Available', 'course': 'Not Available'}
24. del vs pop()
Feature del pop()
Removes item Yes Yes
Returns removed value No Yes
Can provide default value No Yes
25. Practical Example
student = {
    "name": "Rahul",
    "course": "Python",
    "fees": 5000
}

print("Name:", student.get("name"))

student.update({"fees": 6000})

print("Updated Fees:", student["fees"])

for key, value in student.items():
    print(key, ":", value)
Output:
Name: Rahul
Updated Fees: 6000
name : Rahul
course : Python
fees : 6000
26. Key Points
  • get() retrieves a value safely.
  • keys() returns dictionary keys.
  • values() returns dictionary values.
  • items() returns key-value pairs.
  • update() adds or changes items.
  • pop() removes a specified key and returns its value.
  • popitem() removes and returns the last inserted key-value pair.
  • clear() removes all dictionary items.
  • copy() creates a shallow copy.
  • setdefault() retrieves a value or creates a key with a default value.
  • fromkeys() creates a dictionary from a sequence of keys.

🧠 Quick Quiz

Question: Which dictionary method returns all key-value pairs?