Class 12 Computer Science - Python Dictionaries
A Dictionary is an unordered, mutable collection of key-value pairs.
1. Creating a Dictionary
student = {
"name": "Rahul",
"roll_no": 101,
"marks": 95
}2. Important Methods
dict.keys(): Returns all the keys.dict.values(): Returns all the values.dict.items(): Returns key-value pairs as tuples.dict.get(key): Returns value for a key without raising an error if key is missing.dict.pop(key): Removes the specified key and returns the value.
3. Merging Dictionaries
In Python 3.9+, you can use the union operator:
dict3 = dict1 | dict24. Dictionary Comprehension
squares = {x: x*x for x in range(1, 6)}
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}5. Board Exam Typical Question
Question: Write a function to count the frequency of each character in a string using a dictionary.
def count_freq(s):
freq = {}
for char in s:
freq[char] = freq.get(char, 0) + 1
return freqTip: Remember that keys in a dictionary must be immutable (Strings, Numbers, Tuples). 🐍💻
Student Feedback
SR
Sameer Rajput
Verified Student
2 days ago
"Literally saved my internal exams. The diagrams and cheat sheets included are so clear! High quality material."
NG
Nisha Gupta
Verified Student
1 week ago
"Best notes for JEE preparation. Concise, accurate, and exactly what I needed for last-minute revision."