Class - XII: SEMESTER – III: Unit – 1: Python Programming: Section 12: Dictionary (COMS Only)
Python Programming: Dictionary
১. Dictionary কী?
Python programming language-এ Dictionary হলো একটি built-in data structure, যেখানে data key-value pair আকারে store করা হয়। অর্থাৎ প্রতিটি value-এর সাথে একটি unique key থাকে, এবং সেই key ব্যবহার করে value access করা যায়।
Dictionary অনেকটা বাস্তব জীবনের dictionary বা phone book-এর মতো। যেমন একটি phone book-এ একজন মানুষের নাম দিয়ে তার phone number খুঁজে পাওয়া যায়। ঠিক তেমনি Python dictionary-তে key ব্যবহার করে value খুঁজে পাওয়া যায়।
Python dictionary curly braces { } ব্যবহার করে তৈরি করা হয়। প্রতিটি item-এর format হলো
key: value। একাধিক key-value pair comma দিয়ে আলাদা করা হয়।
Example:
student = {
"name": "Rahim",
"age": 20,
"marks": 85
}
print(student)
এখানে "name", "age", এবং "marks" হলো keys।
আর "Rahim", 20, এবং 85 হলো values।
২. Dictionary-এর বৈশিষ্ট্য
- Dictionary key-value pair আকারে data store করে।
- Dictionary mutable — item add, update এবং delete করা যায়।
- Dictionary-এর keys unique হতে হয়। একই key আবার দিলে পুরনো value replace হয়ে যায়।
- Dictionary ordered collection — Python-এর modern versions-এ insertion order preserve করে।
- Dictionary indexing support করে না, কারণ list বা tuple-এর মতো numeric index দিয়ে item access করা যায় না।
- Dictionary value যেকোনো data type হতে পারে — string, number, list, tuple, another dictionary ইত্যাদি।
- Dictionary key সাধারণত immutable type হতে হয়, যেমন string, number বা tuple।
Duplicate Key Example:
student = {
"name": "Rahim",
"age": 20,
"age": 21
}
print(student)
Output:
{'name': 'Rahim', 'age': 21}
এখানে "age" key দুইবার দেওয়া হয়েছে। Python শেষ value 21 রাখবে।
৩. Dictionary তৈরি করার পদ্ধতি
Python-এ dictionary বিভিন্নভাবে তৈরি করা যায়। সবচেয়ে common পদ্ধতি হলো curly braces ব্যবহার করা।
এছাড়াও dict() constructor ব্যবহার করেও dictionary তৈরি করা যায়।
Curly braces ব্যবহার করে:
person = {
"name": "Karim",
"city": "Dhaka",
"age": 25
}
print(person)
dict() ব্যবহার করে:
person = dict(name="Karim", city="Dhaka", age=25)
print(person)
Empty Dictionary:
data = {}
print(data)
Empty dictionary তৈরি করার জন্য {} ব্যবহার করা হয়।
{} dictionary তৈরি করে, set নয়।
Empty set তৈরি করতে set() ব্যবহার করতে হয়।
৪. Accessing Items in a Dictionary using Keys
Dictionary-এর item access করার জন্য key ব্যবহার করা হয়। List-এর মতো index দিয়ে dictionary access করা যায় না। Dictionary-এর key ব্যবহার করলে সেই key-এর corresponding value পাওয়া যায়।
Square bracket ব্যবহার করে:
student = {
"name": "Rahim",
"age": 20,
"marks": 85
}
print(student["name"])
print(student["age"])
print(student["marks"])
Output:
Rahim
20
85
এখানে student["name"] key ব্যবহার করে value Rahim access করা হয়েছে।
Key না থাকলে কী হয়?
student = {
"name": "Rahim",
"age": 20
}
print(student["marks"])
এই code KeyError দেবে, কারণ "marks" key dictionary-এর মধ্যে নেই।
get() method ব্যবহার করা ভালো।
৫. get() Method
get() method dictionary থেকে value access করার safe method।
যদি key dictionary-এর মধ্যে থাকে, তাহলে value return করে। যদি key না থাকে, তাহলে default value return করতে পারে।
Example:
student = {
"name": "Rahim",
"age": 20
}
print(student.get("name"))
print(student.get("marks"))
Output:
Rahim
None
এখানে "marks" key নেই, তাই None return হয়েছে।
Default Value সহ get():
student = {
"name": "Rahim",
"age": 20
}
marks = student.get("marks", "Marks not available")
print(marks)
Output:
Marks not available
৬. Mutability of Dictionary
Dictionary mutable data structure। অর্থাৎ dictionary তৈরি করার পরে এর মধ্যে নতুন key-value pair add করা যায়, existing key-এর value modify করা যায় এবং item delete করা যায়।
৬.১ Adding a New Term
Dictionary-তে নতুন item add করার জন্য নতুন key assign করতে হয়।
student = {
"name": "Rahim",
"age": 20
}
student["marks"] = 85
print(student)
Output:
{'name': 'Rahim', 'age': 20, 'marks': 85}
এখানে "marks" নামে নতুন key add হয়েছে।
৬.২ Modifying an Existing Item
Existing key-এর value change করতে সেই key-তে নতুন value assign করতে হয়।
student = {
"name": "Rahim",
"age": 20,
"marks": 85
}
student["marks"] = 90
print(student)
Output:
{'name': 'Rahim', 'age': 20, 'marks': 90}
এখানে "marks" key-এর value 85 থেকে 90 হয়েছে।
৭. Traversing a Dictionary
Dictionary-এর প্রতিটি key, value বা key-value pair loop ব্যবহার করে access করাকে dictionary traversal বলা হয়।
Dictionary traverse করার জন্য for loop ব্যবহার করা হয়।
Only Keys Traversal:
student = {
"name": "Rahim",
"age": 20,
"marks": 85
}
for key in student:
print(key)
Output:
name
age
marks
Values Traversal:
student = {
"name": "Rahim",
"age": 20,
"marks": 85
}
for value in student.values():
print(value)
Output:
Rahim
20
85
Key-Value Pair Traversal:
student = {
"name": "Rahim",
"age": 20,
"marks": 85
}
for key, value in student.items():
print(key, ":", value)
Output:
name : Rahim
age : 20
marks : 85
৮. len()
len() function dictionary-এর total key-value pair সংখ্যা return করে।
student = {
"name": "Rahim",
"age": 20,
"marks": 85
}
print(len(student))
Output:
3
এখানে dictionary-তে ৩টি key-value pair আছে।
৯. dict()
dict() function dictionary তৈরি করতে ব্যবহার করা হয়।
এটি keyword arguments, list of tuples, বা অন্য mapping object থেকে dictionary তৈরি করতে পারে।
Using keyword arguments:
student = dict(name="Rahim", age=20, marks=85)
print(student)
Using list of tuples:
pairs = [("name", "Karim"), ("age", 21), ("marks", 90)]
student = dict(pairs)
print(student)
Output:
{'name': 'Karim', 'age': 21, 'marks': 90}
১০. keys(), values(), items()
Dictionary-এর keys, values এবং key-value pairs access করার জন্য এই তিনটি method খুব গুরুত্বপূর্ণ।
| Method | কাজ | Example |
|---|---|---|
keys() |
Dictionary-এর সব keys return করে | student.keys() |
values() |
Dictionary-এর সব values return করে | student.values() |
items() |
Dictionary-এর সব key-value pairs return করে | student.items() |
Example:
student = {
"name": "Rahim",
"age": 20,
"marks": 85
}
print(student.keys())
print(student.values())
print(student.items())
Output:
dict_keys(['name', 'age', 'marks'])
dict_values(['Rahim', 20, 85])
dict_items([('name', 'Rahim'), ('age', 20), ('marks', 85)])
১১. update()
update() method dictionary-তে এক বা একাধিক key-value pair add বা update করতে ব্যবহার করা হয়।
যদি key আগে থেকেই থাকে, তাহলে value update হয়। যদি key না থাকে, তাহলে নতুন item add হয়।
Example:
student = {
"name": "Rahim",
"age": 20
}
student.update({"marks": 85, "city": "Dhaka"})
print(student)
Output:
{'name': 'Rahim', 'age': 20, 'marks': 85, 'city': 'Dhaka'}
Existing Value Update:
student = {
"name": "Rahim",
"marks": 85
}
student.update({"marks": 90})
print(student)
Output:
{'name': 'Rahim', 'marks': 90}
১২. del এবং del()
Python-এ del একটি keyword, function নয়। এটি dictionary থেকে নির্দিষ্ট key delete করতে বা পুরো dictionary delete করতে ব্যবহার করা হয়।
অনেক সময় syllabus-এ del() লেখা থাকে, কিন্তু Python-এ correct form হলো del dictionary[key]।
Specific Item Delete:
student = {
"name": "Rahim",
"age": 20,
"marks": 85
}
del student["age"]
print(student)
Output:
{'name': 'Rahim', 'marks': 85}
Whole Dictionary Delete:
student = {
"name": "Rahim",
"age": 20
}
del student
# print(student) # এটি error দেবে, কারণ dictionary delete হয়ে গেছে
del ব্যবহার করলে item বা object পুরোপুরি delete হয়।
কিন্তু clear() dictionary object রাখে, শুধু তার contents remove করে।
১৩. clear()
clear() method dictionary-এর সব items remove করে dictionary empty করে দেয়।
student = {
"name": "Rahim",
"age": 20,
"marks": 85
}
student.clear()
print(student)
Output:
{}
১৪. fromkeys()
fromkeys() method একটি sequence of keys থেকে নতুন dictionary তৈরি করে।
সব keys-এর জন্য একই default value assign করা যায়।
Example:
keys = ["name", "age", "marks"]
student = dict.fromkeys(keys)
print(student)
Output:
{'name': None, 'age': None, 'marks': None}
Default Value সহ:
subjects = ["Bangla", "English", "Math"]
marks = dict.fromkeys(subjects, 0)
print(marks)
Output:
{'Bangla': 0, 'English': 0, 'Math': 0}
১৫. copy()
copy() method dictionary-এর shallow copy তৈরি করে।
এর ফলে original dictionary পরিবর্তন না করে copied dictionary-তে কাজ করা যায়।
student = {
"name": "Rahim",
"age": 20
}
new_student = student.copy()
new_student["age"] = 21
print("Original:", student)
print("Copy:", new_student)
Output:
Original: {'name': 'Rahim', 'age': 20}
Copy: {'name': 'Rahim', 'age': 21}
copy() shallow copy তৈরি করে। যদি dictionary-এর value হিসেবে nested mutable object থাকে,
তাহলে deep copy দরকার হতে পারে।
১৬. pop()
pop() method dictionary থেকে নির্দিষ্ট key-এর item remove করে এবং removed value return করে।
Example:
student = {
"name": "Rahim",
"age": 20,
"marks": 85
}
removed_value = student.pop("age")
print("Removed:", removed_value)
print(student)
Output:
Removed: 20
{'name': 'Rahim', 'marks': 85}
Default Value সহ pop():
student = {
"name": "Rahim",
"age": 20
}
removed_value = student.pop("marks", "Key not found")
print(removed_value)
Output:
Key not found
১৭. popitem()
popitem() method dictionary থেকে শেষ inserted key-value pair remove করে এবং tuple আকারে return করে।
Example:
student = {
"name": "Rahim",
"age": 20,
"marks": 85
}
removed_item = student.popitem()
print("Removed item:", removed_item)
print(student)
Output:
Removed item: ('marks', 85)
{'name': 'Rahim', 'age': 20}
popitem() ব্যবহার করলে error হবে।
১৮. setdefault()
setdefault() method key dictionary-তে থাকলে তার value return করে।
আর key না থাকলে key add করে default value assign করে।
Key already exists:
student = {
"name": "Rahim",
"age": 20
}
value = student.setdefault("age", 25)
print(value)
print(student)
Output:
20
{'name': 'Rahim', 'age': 20}
Key does not exist:
student = {
"name": "Rahim",
"age": 20
}
value = student.setdefault("marks", 0)
print(value)
print(student)
Output:
0
{'name': 'Rahim', 'age': 20, 'marks': 0}
১৯. max(), min() এবং sorted()
Dictionary-এর উপর max(), min() এবং sorted() function ব্যবহার করলে by default keys-এর উপর কাজ করে।
অর্থাৎ dictionary-এর keys compare বা sort করা হয়।
Example:
marks = {
"Rahim": 85,
"Karim": 90,
"Salma": 78
}
print(max(marks))
print(min(marks))
print(sorted(marks))
Output:
Salma
Karim
['Karim', 'Rahim', 'Salma']
এখানে keys alphabetically compare হয়েছে। তাই max() এবং min() keys-এর ভিত্তিতে result দিয়েছে।
Values-এর উপর max/min:
marks = {
"Rahim": 85,
"Karim": 90,
"Salma": 78
}
print(max(marks.values()))
print(min(marks.values()))
Highest Marks Student:
marks = {
"Rahim": 85,
"Karim": 90,
"Salma": 78
}
top_student = max(marks, key=marks.get)
print("Top Student:", top_student)
print("Marks:", marks[top_student])
Sorted by Keys:
marks = {
"Rahim": 85,
"Karim": 90,
"Salma": 78
}
for name in sorted(marks):
print(name, marks[name])
২০. Dictionary Methods Summary Table
| Function / Method | কাজ | Example |
|---|---|---|
len() |
Dictionary-এর key-value pair সংখ্যা দেয় | len(student) |
dict() |
Dictionary তৈরি করে | dict(name="Rahim") |
keys() |
সব keys return করে | student.keys() |
values() |
সব values return করে | student.values() |
items() |
সব key-value pairs return করে | student.items() |
get() |
Key দিয়ে safely value access করে | student.get("name") |
update() |
Item add বা update করে | student.update({"age": 21}) |
del |
Key বা dictionary delete করে | del student["age"] |
clear() |
সব items remove করে | student.clear() |
fromkeys() |
Keys থেকে dictionary তৈরি করে | dict.fromkeys(keys, 0) |
copy() |
Dictionary-এর shallow copy তৈরি করে | student.copy() |
pop() |
Key অনুযায়ী item remove করে value return করে | student.pop("age") |
popitem() |
Last inserted item remove করে | student.popitem() |
setdefault() |
Key না থাকলে add করে default value দেয় | student.setdefault("marks", 0) |
max() |
By default maximum key return করে | max(student) |
min() |
By default minimum key return করে | min(student) |
sorted() |
Keys sorted list হিসেবে return করে | sorted(student) |
২১. Suggested Program ১: Student Marks Dictionary
এই program-এ students-এর marks dictionary-তে store করা হয়েছে। এরপর highest marks, lowest marks এবং average marks বের করা হয়েছে।
marks = {
"Rahim": 85,
"Karim": 90,
"Salma": 78,
"Jamal": 88
}
print("Student Marks:", marks)
highest_marks = max(marks.values())
lowest_marks = min(marks.values())
average_marks = sum(marks.values()) / len(marks)
top_student = max(marks, key=marks.get)
print("Highest Marks:", highest_marks)
print("Lowest Marks:", lowest_marks)
print("Average Marks:", average_marks)
print("Top Student:", top_student)
Explanation:
- Student names keys হিসেবে এবং marks values হিসেবে store করা হয়েছে।
max(marks.values())দিয়ে highest marks বের করা হয়েছে।min(marks.values())দিয়ে lowest marks বের করা হয়েছে।sum()এবংlen()ব্যবহার করে average marks বের করা হয়েছে।max(marks, key=marks.get)দিয়ে highest marks পাওয়া student বের করা হয়েছে।
২২. Suggested Program ২: Counting Frequency of Words
Dictionary frequency counting-এর জন্য খুব useful। কোনো sentence-এ কোন word কতবার এসেছে তা dictionary ব্যবহার করে সহজে count করা যায়।
sentence = input("একটি sentence লিখুন: ")
words = sentence.split()
frequency = {}
for word in words:
if word in frequency:
frequency[word] = frequency[word] + 1
else:
frequency[word] = 1
print("Word Frequency:")
for word, count in frequency.items():
print(word, ":", count)
Explanation:
- User থেকে একটি sentence input নেওয়া হয়েছে।
split()দিয়ে sentence-কে words list-এ convert করা হয়েছে।- প্রতিটি word dictionary-এর key হিসেবে use করা হয়েছে।
- যদি word আগে থেকেই থাকে, count 1 বাড়ানো হয়েছে।
- যদি word না থাকে, নতুন key হিসেবে add করে value 1 রাখা হয়েছে।
২৩. Suggested Program ৩: Simple Phone Book
Dictionary ব্যবহার করে simple phone book তৈরি করা যায়, যেখানে name key এবং phone number value হিসেবে থাকে।
phone_book = {
"Rahim": "01711111111",
"Karim": "01822222222",
"Salma": "01933333333"
}
name = input("কার number খুঁজবেন? ")
number = phone_book.get(name, "Number not found")
print(number)
এখানে get() ব্যবহার করা হয়েছে যাতে name না থাকলে error না আসে।
২৪. Complete Practice Program
নিচের program-এ dictionary creation, access, add, update, traversal, get, keys, values, items, pop, setdefault এবং sorted — একসাথে দেখানো হয়েছে।
student = {
"name": "Rahim",
"age": 20,
"marks": 85
}
print("Original Dictionary:", student)
print("Name:", student["name"])
print("Marks:", student.get("marks"))
student["city"] = "Dhaka"
student["marks"] = 90
print("After adding and modifying:", student)
student.update({"grade": "A", "section": "Science"})
print("After update:", student)
print("Keys:", student.keys())
print("Values:", student.values())
print("Items:", student.items())
print("Traversing Dictionary:")
for key, value in student.items():
print(key, ":", value)
removed_age = student.pop("age")
print("Removed age:", removed_age)
print("After pop:", student)
student.setdefault("attendance", 0)
print("After setdefault:", student)
print("Sorted keys:", sorted(student))
copy_student = student.copy()
print("Copied Dictionary:", copy_student)
student.clear()
print("After clear:", student)
Program Explanation:
- প্রথমে একটি student dictionary তৈরি করা হয়েছে।
- Key ব্যবহার করে value access করা হয়েছে।
- নতুন key-value pair add করা হয়েছে এবং existing value modify করা হয়েছে।
update()দিয়ে একাধিক item add করা হয়েছে।keys(),values(),items()ব্যবহার করা হয়েছে।- Loop দিয়ে dictionary traverse করা হয়েছে।
pop()দিয়ে item remove করা হয়েছে।setdefault()দিয়ে missing key add করা হয়েছে।sorted()দিয়ে keys sort করা হয়েছে।copy()দিয়ে copy তৈরি করা হয়েছে।clear()দিয়ে dictionary empty করা হয়েছে।
২৫. Common Mistakes in Dictionary
- Wrong key access: Dictionary-তে key না থাকলে square bracket access করলে
KeyErrorহয়। - get() ব্যবহার না করা: Safe access-এর জন্য
get()ব্যবহার করা ভালো। - Duplicate key ব্যবহার: একই key আবার দিলে previous value replace হয়ে যায়।
- Mutable object key হিসেবে ব্যবহার: List dictionary key হতে পারে না, কারণ list mutable।
- del এবং clear confuse করা:
delitem বা object delete করে,clear()সব item remove করে কিন্তু dictionary রাখে। - max/min dictionary values-এর উপর হবে ভাবা: Dictionary-তে
max(),min()by default keys-এর উপর কাজ করে। - popitem() empty dictionary-তে ব্যবহার: Empty dictionary হলে error হয়।
Safe Access Example:
student = {
"name": "Rahim",
"age": 20
}
marks = student.get("marks", "Marks not available")
print(marks)
২৬. Dictionary vs List
Dictionary এবং list দুটোই collection data type, কিন্তু এদের ব্যবহার আলাদা। List index-based, আর dictionary key-based। যখন ordered collection দরকার এবং item access index দিয়ে করা হবে, তখন list useful। কিন্তু যখন meaningful key দিয়ে data access করতে হবে, তখন dictionary বেশি useful।
| বিষয় | Dictionary | List |
|---|---|---|
| Data format | Key-value pair | Single values collection |
| Access method | Key ব্যবহার করে | Index ব্যবহার করে |
| Syntax | {"name": "Rahim"} |
["Rahim", "Karim"] |
| Best use | Records, mappings, lookup table | Sequence data, ordered values |
| Example | Student profile, phone book | Marks list, names list |
২৭. উপসংহার
Python dictionary একটি অত্যন্ত powerful এবং practical data structure। এটি key-value pair আকারে data store করে, যার ফলে data access করা অনেক সহজ এবং meaningful হয়। Student record, phone book, product price list, word frequency count, configuration settings, JSON-like data — এসব ক্ষেত্রে dictionary ব্যাপকভাবে ব্যবহৃত হয়।
Dictionary mutable হওয়ার কারণে আমরা নতুন item add করতে পারি, existing item modify করতে পারি এবং unwanted item delete করতে পারি।
Dictionary access করার জন্য key ব্যবহার করা হয়, আর safe access-এর জন্য get() method খুব useful।
Dictionary traverse করার জন্য keys(), values(), এবং items() method গুরুত্বপূর্ণ।
Built-in methods যেমন update(), pop(), popitem(), setdefault(),
copy(), clear(), এবং fromkeys() dictionary handling-কে আরও flexible করে।
max(), min(), এবং sorted() by default keys-এর উপর কাজ করে — এটি মনে রাখা গুরুত্বপূর্ণ।
একজন beginner programmer-এর জন্য dictionary ভালোভাবে শেখা খুব জরুরি, কারণ real-world software development-এ structured data, lookup operations, frequency counting এবং data mapping-এর জন্য dictionary সবচেয়ে বেশি ব্যবহৃত Python data structure-এর একটি।