Unit 5 · Advanced Topics
Dictionary Methods
Master all built-in dictionary methods in Python — from keys() and values() to get(), update(), pop(), and dictionary comprehensions. Essential for university exams and competitive programming.
Table of Contents
Introduction to Dictionary Methods
Python dictionaries are one of the most versatile data structures. They store data as key-value pairs and provide a rich set of built-in methods for manipulation. Understanding these methods is critical for exam success and real-world programming.
University Definition
A dictionary method is a built-in function associated with a dictionary object that performs specific operations such as adding, removing, searching, or transforming key-value pairs. These methods allow efficient data manipulation without directly accessing the underlying hash table.
Dictionary methods can be categorized into groups:
- Access methods: keys(), values(), items(), get()
- Modification methods: update(), setdefault()
- Removal methods: pop(), popitem(), clear()
- Copying methods: copy()
- Creation methods: fromkeys()
keys(), values(), and items()
University Definition
The keys() method returns a view object displaying all keys in the dictionary. The values() method returns a view object with all values. The items() method returns a view object displaying all key-value pairs as tuples.
keys() Method
Returns a view object that displays a list of all the keys in the dictionary.
student = {"name": "Rahul", "age": 20, "grade": "A", "city": "Mumbai"}
# Getting all keys
all_keys = student.keys()
print(all_keys)
print(type(all_keys))
# Iterating through keys
for key in student.keys():
print(key, "->", student[key])
# Using keys directly in a for loop (implicit keys())
for key in student:
print(f"{key}: {student[key]}")
Output:
dict_keys(['name', 'age', 'grade', 'city']) <class 'dict_keys'> name -> Rahul age -> 20 grade -> A city -> Mumbai name: Rahul age: 20 grade: A city: Mumbai
values() Method
Returns a view object that displays a list of all values in the dictionary.
marks = {"Math": 95, "Science": 88, "English": 76, "Hindi": 92}
# Getting all values
all_values = marks.values()
print(all_values)
# Calculate average marks
avg = sum(marks.values()) / len(marks)
print(f"Average marks: {avg}")
# Check if a value exists
if 95 in marks.values():
print("Found a student with 95 marks!")
Output:
dict_values([95, 88, 76, 92]) Average marks: 87.75 Found a student with 95 marks!
items() Method
Returns a view object that displays a list of dictionary key-value tuple pairs.
phone = {"brand": "Samsung", "model": "Galaxy S24", "price": 79999, "ram": "12GB"}
# Getting all items as tuples
all_items = phone.items()
print(all_items)
# Iterating through items
for key, value in phone.items():
print(f"{key.upper()}: {value}")
# Finding an item by value
result = [(k, v) for k, v in phone.items() if v == "12GB"]
print("Items with 12GB:", result)
Output:
dict_items([('brand', 'Samsung'), ('model', 'Galaxy S24'), ('price', 79999), ('ram', '12GB')])
BRAND: Samsung
MODEL: Galaxy S24
PRICE: 79999
RAM: 12GB
Items with 12GB: [('ram', '12GB')]
University Exam Tip
keys(), values(), and items() return view objects, not lists. View objects reflect changes made to the dictionary dynamically. To get a static list, convert using list(). This is a common MCQ question in university exams.
get() Method
University Definition
The get() method returns the value for the specified key if the key exists in the dictionary; otherwise, it returns a default value (None by default). This prevents the KeyError exception.
Syntax
dictionary.get(key, default_value)
student = {"name": "Priya", "age": 21, "course": "B.Tech CSE"}
# Using get() - key exists
print(student.get("name")) # Returns value
print(student.get("course")) # Returns value
# Using get() - key does not exist
print(student.get("phone")) # Returns None
print(student.get("phone", "N/A")) # Returns "N/A"
# Using get() vs direct access
# student["address"] # This would raise KeyError!
print(student.get("address", "Not Available")) # Safe access
# Practical example: counting characters
text = "programming"
char_count = {}
for char in text:
char_count[char] = char_count.get(char, 0) + 1
print(char_count)
Output:
Priya
B.Tech CSE
None
N/A
Not Available
{'p': 1, 'r': 2, 'o': 1, 'g': 2, 'a': 1, 'm': 2, 'i': 1, 'n': 1}
University Exam Tip
The get() method is preferred over direct key access (dict[key]) when the key might not exist. This is a best practice question frequently asked in exams. Always use get() with a default value for safe data retrieval.
update() Method
University Definition
The update() method updates the dictionary with elements from another dictionary object or from an iterable of key-value pairs. If the key already exists, the value is updated; otherwise, a new key-value pair is added.
student = {"name": "Amit", "age": 20, "city": "Delhi"}
# Update with another dictionary
new_data = {"age": 21, "grade": "A+", "city": "Bangalore"}
student.update(new_data)
print("After update:", student)
# Update with keyword arguments (Python 3.9+)
student.update(phone="9876543210", email="amit@email.com")
print("After keyword update:", student)
# Update with a list of tuples
details = [("course", "B.Tech"), ("year", 3)]
student.update(details)
print("After list update:", student)
# Merge two dictionaries (Python 3.9+ using |)
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = dict1 | dict2 # dict2 values override dict1 for common keys
print("Merged:", merged)
Output:
After update: {'name': 'Amit', 'age': 21, 'city': 'Bangalore', 'grade': 'A+'}
After keyword update: {'name': 'Amit', 'age': 21, 'city': 'Bangalore', 'grade': 'A+', 'phone': '9876543210', 'email': 'amit@email.com'}
After list update: {'name': 'Amit', 'age': 21, 'city': 'Bangalore', 'grade': 'A+', 'phone': '9876543210', 'email': 'amit@email.com', 'course': 'B.Tech', 'year': 3}
Merged: {'a': 1, 'b': 3, 'c': 4}
pop() and popitem()
University Definition
The pop() method removes the specified key and returns its value. If the key is not found, it returns a default value (or raises KeyError if no default is given). The popitem() method removes and returns the last inserted key-value pair as a tuple.
inventory = {"laptop": 50000, "phone": 25000, "tablet": 15000, "watch": 8000}
# pop() - removes key and returns value
price = inventory.pop("tablet")
print(f"Removed tablet: {price}")
print("Inventory:", inventory)
# pop() with default value
value = inventory.pop("camera", "Not in stock")
print(f"Camera: {value}")
# pop() without default (would raise KeyError if key missing)
# inventory.pop("nonexistent") # Uncomment to see error
# popitem() - removes last inserted pair
last_item = inventory.popitem()
print(f"Last item removed: {last_item}")
print("Inventory:", inventory)
# popitem() on empty dict raises KeyError
# empty = {}
# empty.popitem() # KeyError
# Practical example: processing a queue
tasks = {"task1": "High", "task2": "Medium", "task3": "Low", "task4": "High"}
while tasks:
task, priority = tasks.popitem()
print(f"Processing {task} (Priority: {priority})")
Output:
Removed tablet: 15000
Inventory: {'laptop': 50000, 'phone': 25000, 'watch': 8000}
Camera: Not in stock
Last item removed: ('watch', 8000)
Inventory: {'laptop': 50000, 'phone': 25000}
Processing task4 (Priority: High)
Processing task3 (Priority: Low)
Processing task2 (Priority: Medium)
Processing task1 (Priority: High)
University Exam Tip
Key difference: pop(key) removes a specific key, while popitem() removes the last inserted pair. In Python 3.7+, dictionaries maintain insertion order. This is a frequent short-answer question. Always provide a default value with pop() to avoid KeyError.
clear() and copy()
University Definition
The clear() method removes all key-value pairs from the dictionary, making it an empty dictionary. The copy() method returns a shallow copy of the dictionary — a new dictionary with the same key-value pairs.
# clear() method
config = {"debug": True, "version": "2.0", "host": "localhost"}
print("Before clear:", config)
config.clear()
print("After clear:", config)
print("Is empty:", len(config) == 0)
# copy() - shallow copy
original = {"name": "Python", "version": 3.12, "features": ["OOP", "Functional", "Procedural"]}
# This is NOT a copy - it's just another reference
reference = original
reference["version"] = 3.11
print("Original after ref change:", original) # Also changed!
# This IS a copy (shallow)
copied = original.copy()
copied["version"] = 3.10
print("Original after copy change:", original) # NOT changed
print("Copied dict:", copied)
# Shallow copy caveat - nested objects are shared
original = {"name": "Alice", "scores": [90, 85, 92]}
shallow = original.copy()
shallow["scores"].append(88)
print("Original scores:", original["scores"]) # Also has 88!
print("Shallow scores:", shallow["scores"])
# For deep copy, use copy module
import copy
original = {"name": "Bob", "scores": [78, 82]}
deep = copy.deepcopy(original)
deep["scores"].append(95)
print("Original deep:", original["scores"]) # Not changed
print("Deep copy:", deep["scores"]) # Has 95
Output:
Before clear: {'debug': True, 'version': '2.0', 'host': 'localhost'}
After clear: {}
Is empty: True
Original after ref change: {'name': 'Python', 'version': 3.11, 'features': ['OOP', 'Functional', 'Procedural']}
Original after copy change: {'name': 'Python', 'version': 3.11, 'features': ['OOP', 'Functional', 'Procedural']}
Copied dict: {'name': 'Python', 'version': 3.10, 'features': ['OOP', 'Functional', 'Procedural']}
Original scores: [90, 85, 92, 88]
Shallow scores: [90, 85, 92, 88]
Original deep: [78, 82]
Deep copy: [78, 82, 95]
setdefault() and fromkeys()
University Definition
The setdefault() method returns the value of a key if it exists; otherwise, it inserts the key with a specified default value and returns that value. The fromkeys() is a class method that creates a new dictionary with keys from an iterable and all values set to a specified default.
setdefault() Method
student = {"name": "Ravi", "age": 22}
# Key exists - returns existing value, does NOT change
age = student.setdefault("age", 20)
print(f"Age: {age}")
print("Student:", student)
# Key does not exist - adds key with default value
grade = student.setdefault("grade", "B")
print(f"Grade: {grade}")
print("Student:", student)
# Practical: Grouping items by category
words = ["apple", "ant", "banana", "bat", "cherry", "cat"]
grouped = {}
for word in words:
first_letter = word[0]
grouped.setdefault(first_letter, []).append(word)
print("Grouped:", grouped)
# Counting occurrences efficiently
sentences = ["hello world", "hello python", "world of python"]
word_freq = {}
for sentence in sentences:
for word in sentence.split():
word_freq[word] = word_freq.get(word, 0) + 1
print("Word frequency:", word_freq)
Output:
Age: 22
Student: {'name': 'Ravi', 'age': 22}
Grade: B
Student: {'name': 'Ravi', 'age': 22, 'grade': 'B'}
Grouped: {'a': ['apple', 'ant'], 'b': ['banana', 'bat'], 'c': ['cherry', 'cat']}
Word frequency: {'hello': 2, 'world': 2, 'python': 2, 'of': 1}
fromkeys() Method
# Creating a dictionary with default values
keys = ["name", "age", "city"]
default_dict = dict.fromkeys(keys, "Unknown")
print("Default dict:", default_dict)
# fromkeys with None (default)
keys = ["a", "b", "c"]
none_dict = dict.fromkeys(keys)
print("None dict:", none_dict)
# fromkeys with mutable default (caution!)
keys = ["students", "teachers", "admins"]
shared_list = dict.fromkeys(keys, [])
shared_list["students"].append("Alice")
print("Shared list:", shared_list) # All keys share same list!
# Safe way with dict comprehension
safe = {key: [] for key in keys}
safe["students"].append("Bob")
print("Safe dict:", safe)
# fromkeys with range
squares = dict.fromkeys(range(1, 6), 0)
print("Squares init:", squares)
# Initialize scores for students
students = ["Rahul", "Priya", "Amit"]
scores = dict.fromkeys(students, 0)
print("Initial scores:", scores)
Output:
Default dict: {'name': 'Unknown', 'age': 'Unknown', 'city': 'Unknown'}
None dict: {'a': None, 'b': None, 'c': None}
Shared list: {'students': ['Alice'], 'teachers': ['Alice'], 'admins': ['Alice']}
Safe dict: {'students': ['Bob'], 'teachers': [], 'admins': []}
Squares init: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
Initial scores: {'Rahul': 0, 'Priya': 0, 'Amit': 0}
University Exam Tip
Important: Never use a mutable object (list, dict) as the default value in fromkeys() — all keys will share the same object. Use a dict comprehension instead. Also, setdefault() is equivalent to get() + assignment and is useful for grouping operations.
Dictionary Comprehensions
Dictionary comprehensions provide a concise way to create dictionaries. They are similar to list comprehensions but use curly braces {} with a colon : for key-value pairs.
Syntax
{key_expression: value_expression for item in iterable if condition}
# Basic comprehension
squares = {x: x**2 for x in range(1, 11)}
print("Squares:", squares)
# With condition - even numbers only
even_squares = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print("Even squares:", even_squares)
# Transform a dictionary
prices = {"apple": 50, "banana": 30, "cherry": 80, "date": 120}
discounted = {item: price * 0.9 for item, price in prices.items()}
print("Discounted:", {k: round(v, 1) for k, v in discounted.items()})
# Filter expensive items
expensive = {k: v for k, v in prices.items() if v > 50}
print("Expensive items:", expensive)
# Invert dictionary
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print("Inverted:", inverted)
# From two lists
names = ["Rahul", "Priya", "Amit"]
scores = [85, 92, 78]
grade_book = {name: score for name, score in zip(names, scores)}
print("Grade book:", grade_book)
# Nested comprehension - matrix transpose
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose = [[row[i] for row in matrix] for i in range(3)]
print("Original:", matrix)
print("Transposed:", transpose)
Output:
Squares: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
Even squares: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
Discounted: {'apple': 45.0, 'banana': 27.0, 'cherry': 72.0, 'date': 108.0}
Expensive items: {'cherry': 80, 'date': 120}
Inverted: {1: 'a', 2: 'b', 3: 'c'}
Grade book: {'Rahul': 85, 'Priya': 92, 'Amit': 78}
Original: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Transposed: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Dictionary Methods Comparison
| Method | Returns | Modifies Dict? | Key Error Safe? |
|---|---|---|---|
get(key) | Value or None | No | Yes |
keys() | dict_keys view | No | Yes |
values() | dict_values view | No | Yes |
items() | dict_items view | No | Yes |
update() | None | Yes | Yes |
pop(key) | Removed value | Yes | With default |
popitem() | (key, value) tuple | Yes | No |
clear() | None | Yes | Yes |
copy() | New dict (shallow) | No | Yes |
setdefault() | Value | Maybe | Yes |
fromkeys() | New dict | No (class method) | Yes |
Key Points
keys() returns a view object that dynamically reflects dictionary changes.
get() is safer than direct access — avoids KeyError with a default value.
update() merges dictionaries; duplicate keys get overwritten.
pop() removes by key; popitem() removes the last inserted pair.
copy() creates a shallow copy — nested objects are shared.
Use copy.deepcopy() for independent copies of nested dictionaries.
setdefault() is ideal for grouping operations and counting patterns.
Avoid mutable defaults with fromkeys() — all keys share the same object.
Dictionary comprehensions provide a concise way to create and transform dicts.
In Python 3.7+, dictionaries maintain insertion order.
Common Mistakes to Avoid
- Using
dict[key]instead ofdict.get(key)when key may not exist. - Forgetting that
copy()is shallow — nested mutable objects are shared. - Using mutable default values in
fromkeys()causing unexpected shared state. - Assuming
keys(),values(),items()return lists (they return view objects). - Calling
popitem()on an empty dictionary without error handling.
Practice Questions
- Write a program to count the frequency of each character in a string using dictionary methods.
- Create two dictionaries and merge them, handling duplicate keys by keeping the higher value.
- Write a function that takes a list of dictionaries and returns a dictionary grouping items by a specified key.
- Implement a simple cache using
setdefault()that stores function results for repeated calls. - Create a dictionary from two lists — one for keys and one for values — and handle mismatched lengths.
- Write a program that removes all items from a dictionary where the value is less than a given threshold.
Summary
Python dictionary methods provide powerful tools for data manipulation. keys(), values(), and items() offer efficient iteration, while get() provides safe access. update() and setdefault() handle modifications, pop() and popitem() manage removals, and copy() enables duplication. Dictionary comprehensions add a concise way to create and transform dictionaries. Mastering these methods is essential for both academic exams and practical programming.