Python
All Python Dictionary Methods (with Examples and Output)
Complete reference of every Python dictionary method — get, update, pop, keys, values, items, setdefault, fromkeys, with code and output for each.
Dictionaries are one of the most important data structures in the CBSE Class 12 Python syllabus. This guide covers every built-in dictionary method with clear examples and expected output, so you can answer any board exam question with confidence.
What is a Dictionary?
A dictionary stores data as key-value pairs inside curly braces {}. Keys must be unique and immutable (strings, numbers, or tuples). Values can be of any type.
student = {"name": "Aman", "marks": 85, "city": "Delhi"}
1. dict.get(key, default)
Returns the value for a key. If the key does not exist, it returns default instead of raising an error.
student = {"name": "Aman", "marks": 85}
print(student.get("name")) # Key exists
print(student.get("age")) # Key missing, no default
print(student.get("age", 18)) # Key missing, with default
Aman
None
18
Exam Tip: get() is safer than student["age"] because it does not throw a KeyError when the key is absent.
2. dict.keys()
Returns a view object containing all the keys.
student = {"name": "Aman", "marks": 85, "city": "Delhi"}
print(student.keys())
print(list(student.keys()))
dict_keys(['name', 'marks', 'city'])
['name', 'marks', 'city']
3. dict.values()
Returns a view object containing all the values.
student = {"name": "Aman", "marks": 85, "city": "Delhi"}
print(student.values())
print(list(student.values()))
dict_values(['Aman', 85, 'Delhi'])
['Aman', 85, 'Delhi']
4. dict.items()
Returns a view object of all key-value pairs as tuples.
student = {"name": "Aman", "marks": 85, "city": "Delhi"}
print(student.items())
for key, value in student.items():
print(key, "->", value)
dict_items([('name', 'Aman'), ('marks', 85), ('city', 'Delhi')])
name -> Aman
marks -> 85
city -> Delhi
5. dict.update(other_dict)
Adds key-value pairs from another dictionary. If a key already exists, its value is updated.
student = {"name": "Aman", "marks": 85}
student.update({"marks": 90, "city": "Delhi"})
print(student)
{'name': 'Aman', 'marks': 90, 'city': 'Delhi'}
Notice that marks was updated from 85 to 90, and city was added as a new key.
6. dict.pop(key, default)
Removes the key and returns its value. If the key does not exist and no default is given, it raises a KeyError.
student = {"name": "Aman", "marks": 85, "city": "Delhi"}
removed = student.pop("city")
print(removed)
print(student)
safe = student.pop("age", "Not found")
print(safe)
Delhi
{'name': 'Aman', 'marks': 85}
Not found
7. dict.popitem()
Removes and returns the last inserted key-value pair as a tuple. Raises KeyError if the dictionary is empty.
student = {"name": "Aman", "marks": 85, "city": "Delhi"}
last = student.popitem()
print(last)
print(student)
('city', 'Delhi')
{'name': 'Aman', 'marks': 85}
8. dict.setdefault(key, default)
Returns the value of the key if it exists. If the key does not exist, it inserts the key with the given default value and returns that value.
student = {"name": "Aman", "marks": 85}
val1 = student.setdefault("name", "Unknown")
val2 = student.setdefault("city", "Delhi")
print(val1)
print(val2)
print(student)
Aman
Delhi
{'name': 'Aman', 'marks': 85, 'city': 'Delhi'}
Exam Tip: Unlike get(), setdefault() actually modifies the dictionary when the key is missing.
9. dict.clear()
Removes all key-value pairs from the dictionary, making it empty.
student = {"name": "Aman", "marks": 85}
student.clear()
print(student)
{}
10. dict.copy()
Returns a shallow copy of the dictionary. Changes to the copy do not affect the original.
original = {"name": "Aman", "marks": 85}
duplicate = original.copy()
duplicate["marks"] = 90
print(original)
print(duplicate)
{'name': 'Aman', 'marks': 85}
{'name': 'Aman', 'marks': 90}
11. dict.fromkeys(keys, value)
Creates a new dictionary with the given keys, all set to the same value.
subjects = ["Maths", "Physics", "CS"]
marks = dict.fromkeys(subjects, 0)
print(marks)
{'Maths': 0, 'Physics': 0, 'CS': 0}
12. del Statement
Not a method, but frequently tested. Deletes a specific key or the entire dictionary.
student = {"name": "Aman", "marks": 85, "city": "Delhi"}
del student["city"] # Delete one key
print(student)
del student # Delete entire dictionary
# print(student) # NameError: name 'student' is not defined
{'name': 'Aman', 'marks': 85}
13. in and not in Operators
Check whether a key exists in the dictionary.
student = {"name": "Aman", "marks": 85}
print("name" in student)
print("age" in student)
print("age" not in student)
True
False
True
Important: The in operator checks keys only, not values.
Quick Reference Table
| Method | What it Does | Returns |
|---|---|---|
get(key, default) |
Returns value for key | Value or default |
keys() |
All keys | dict_keys object |
values() |
All values | dict_values object |
items() |
All key-value pairs | dict_items of tuples |
update(dict2) |
Merges another dict | None |
pop(key) |
Removes key, returns value | Value |
popitem() |
Removes last pair | Tuple |
setdefault(key, val) |
Gets or inserts key | Value |
clear() |
Empties dictionary | None |
copy() |
Shallow copy | New dict |
fromkeys(keys, val) |
New dict from keys | New dict |
Common Exam Questions
Q1: What is the difference between get() and direct access using []?
Using student["age"] raises a KeyError if the key does not exist. Using student.get("age") returns None instead of raising an error. You can also pass a default value: student.get("age", 0).
Q2: What is the output of the following?
d = {"a": 1, "b": 2, "c": 3}
d.pop("b")
d.update({"d": 4})
print(d)
print(len(d))
{'a': 1, 'c': 3, 'd': 4}
3
Q3: Write the output:
d = {}
d.setdefault("x", []).append(1)
d.setdefault("x", []).append(2)
print(d)
{'x': [1, 2]}
The first call creates key "x" with an empty list, then appends 1. The second call finds the key already exists, returns the existing list, and appends 2.
Q4: Can a tuple be a dictionary key?
Yes, because tuples are immutable. Lists cannot be dictionary keys because they are mutable.
locations = {(28.6, 77.2): "Delhi", (19.0, 72.8): "Mumbai"}
print(locations[(28.6, 77.2)])
Delhi
Tips for the Board Exam
get()vs[]is asked almost every year. Always mention thatget()does not raiseKeyError.- Remember that
keys(),values(), anditems()return view objects, not lists. Convert them withlist()if needed. update()both adds new keys and overwrites existing ones.popitem()removes the last inserted item (Python 3.7+).- Dictionary keys must be immutable, strings, numbers, or tuples are allowed; lists are not.
Mastering these methods will help you handle dictionary-based questions in both the theory paper and practical exam.
Want to learn more?
Explore free chapter-wise notes with quizzes and code playground
Prefer watching over reading?
Subscribe for free.