Python Dictionary Methods

1. What are Dictionary Methods?

Dictionary methods are built-in functions that help us work easily with dictionaries.

They help us to:

  • Add items

  • Remove items

  • Access data

  • Copy dictionaries

2. get() – Get Value Safely

Returns value of a key without error if key is missing.

Example

 

3. keys() – Get All Keys

Example

print(student.keys())

4. values() – Get All Values

Example

print(student.values())

5. items() – Get Key and Value Pairs

Example

print(student.items())

6. update() – Add or Change Items

Adds new items or updates existing ones.

Example

student.update({"city": "Delhi"})
student.update({"age": 21})
print(student)

7. pop() – Remove Item by Key

Example

student.pop("age")
print(student)

Safe Remove

student.pop("phone", None)

8. popitem() – Remove Last Item

Example

student.popitem()
print(student)

9. clear() – Remove All Items

Example

student.clear()
print(student)

10. copy() – Copy Dictionary

Creates a new dictionary copy.

Example

new_student = student.copy()
print(new_student)

11. setdefault() – Get or Add Key

Returns value if key exists, otherwise adds key.

Example

student.setdefault("marks", 0)
print(student)

12. fromkeys() – Create Dictionary from Keys

Example

keys = ["name", "age", "city"]
new_dict = dict.fromkeys(keys, None)
print(new_dict)

13. Common Beginner Mistakes

❌ Using Index Instead of Key

student[0]

❌ Error.

❌ Forgetting Methods Return Type

x = student.keys()

This returns a view, not a list.

14. Simple Practice Examples

Example 1: Add Default Value

data = {}
data.setdefault("count", 1)
print(data)

Example 2: Copy Dictionary

product = {"name": "Laptop", "price": 50000}
backup = product.copy()
print(backup)

Example 3: Remove All Items

product.clear()
print(product)

15. Summary (Dictionary Methods)

get() accesses safely
update() adds or changes
pop() removes items
copy() duplicates dictionary
✔ Dictionary methods save time

📘 Perfect for Beginner eBook

This chapter is ideal for:

  • Python beginner books

  • School & college students

  • Self-learners

If you want next, I can write:

  • Dictionary Exercises

  • Mini Python Projects

  • File Handling

  • Error Handling

Just tell me 😊

You may also like...