Course Progress29%
⏳ 5 min read
Dictionary Methods
keys(), values(), items(), get(), update() — the essential toolkit for working with dictionaries.
"keys(), values(), items() — three methods that unlock everything inside a dictionary. Learn these and you can work with any dict."
— ShurAIThe Big Four Methods
.keys()
Returns all keys in the dictionary
.values()
Returns all values in the dictionary
.items()
Returns all (key, value) pairs — use with loops
.get(key)
Safe lookup — returns None if key missing (no crash)
python — keys, values, items
student = {"name": "Kavya", "score": 91, "city": "Pune"}
print(student.keys()) # dict_keys(['name', 'score', 'city'])
print(student.values()) # dict_values(['Kavya', 91, 'Pune'])
print(student.items()) # dict_items([('name','Kavya'),('score',91),...])
# Most common use — loop with items()
for key, val in student.items():
print(f" {key}: {val}")
get() — Safe Lookup, No Crash
Using dict["key"] raises a KeyError if the key doesn't exist. get() returns None instead — much safer:
python
scores = {"Riya": 88, "Arjun": 75}
# Dangerous — crashes if key missing
# print(scores["Sneha"]) # KeyError!
# Safe — returns None if missing
print(scores.get("Riya")) # 88
print(scores.get("Sneha")) # None
# Provide a default value if key missing
print(scores.get("Sneha", 0)) # 0 (default)
# Practical pattern
name = input("Student name: ")
result = scores.get(name, "not found")
print(f"{name}: {result}")
update() — Merge Another Dict
python
profile = {"name": "Riya", "age": 22}
extra = {"city": "Mumbai", "age": 23} # age will be updated
profile.update(extra)
print(profile)
# {'name': 'Riya', 'age': 23, 'city': 'Mumbai'}
pop() and clear()
python
d = {"a": 1, "b": 2, "c": 3}
# pop() — remove key and return its value
val = d.pop("b")
print(val) # 2
print(d) # {'a': 1, 'c': 3}
# clear() — remove all entries
d.clear()
print(d) # {}
Real Example — Word Frequency Counter
python
sentence = "the cat sat on the mat the cat is fat"
words = sentence.split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
for word, count in sorted(freq.items(), key=lambda x: -x[1]):
print(f" {word:6} x{count}")
output
the x3
cat x2
sat x1
on x1
mat x1
is x1
fat x1
"get() with a default is one of Python's most practical patterns. Use it whenever a key might or might not be there."
— ShurAI🧠 Quiz — Q1
What does dict.get("key", 0) return if "key" does not exist?
🧠 Quiz — Q2
Which method returns (key, value) pairs for looping?
🧠 Quiz — Q3
What does d.pop("name") do?
🧠 Quiz — Q4
In the word-frequency pattern freq.get(word, 0) + 1, what does the 0 do?