Dictionary Comprehension

🐍 Python Dictionary Comprehension (ডিটেইল গাইড)

Python-এ Dictionary Comprehension হলো একটি আধুনিক, সংক্ষিপ্ত ও শক্তিশালী উপায় যার মাধ্যমে খুব সহজে নতুন dictionary তৈরি করা যায়। এটি কোডকে করে তোলে ছোট, পরিষ্কার ও দ্রুত

📌 Dictionary Comprehension কী?

Dictionary Comprehension ব্যবহার করে আমরা এক লাইনে dictionary তৈরি করতে পারি, যেখানে key-value pair থাকে।

🔹 Basic Syntax

{ key : value for item in iterable }
    

📌 Normal Way vs Dictionary Comprehension

প্রথমে সাধারণ পদ্ধতি দেখি:

numbers = [1, 2, 3, 4]
squares = {}

for n in numbers:
    squares[n] = n * n

print(squares)
# Output: {1: 1, 2: 4, 3: 9, 4: 16}
  

Dictionary Comprehension ব্যবহার করলে:

numbers = [1, 2, 3, 4]

squares = {n: n*n for n in numbers}

print(squares)
# Output: {1: 1, 2: 4, 3: 9, 4: 16}
  

📌 Condition সহ Dictionary Comprehension

আমরা চাইলে condition (if) ব্যবহার করে নির্দিষ্ট data filter করতে পারি।

numbers = [1, 2, 3, 4, 5, 6]

even_squares = {n: n*n for n in numbers if n % 2 == 0}

print(even_squares)
# Output: {2: 4, 4: 16, 6: 36}
  

📌 String থেকে Dictionary তৈরি

একটি string থেকে প্রতিটি character এবং তার ASCII value দিয়ে dictionary তৈরি করা যাক।

text = "abc"

ascii_dict = {ch: ord(ch) for ch in text}

print(ascii_dict)
# Output: {'a': 97, 'b': 98, 'c': 99}
  

📌 Two Lists থেকে Dictionary তৈরি

দুটি list ব্যবহার করে key-value dictionary তৈরি করা খুবই কমন কাজ।

keys = ['name', 'age', 'city']
values = ['Rahul', 25, 'Kolkata']

user = {k: v for k, v in zip(keys, values)}

print(user)
# Output: {'name': 'Rahul', 'age': 25, 'city': 'Kolkata'}
  

📌 Dictionary থেকে Dictionary (Transform)

একটি existing dictionary থেকে নতুন dictionary তৈরি করা যায়।

prices = {'apple': 100, 'banana': 40, 'mango': 80}

discounted = {item: price - 10 for item, price in prices.items()}

print(discounted)
# Output: {'apple': 90, 'banana': 30, 'mango': 70}
  

📌 if-else সহ Dictionary Comprehension

marks = {'Rahul': 85, 'Amit': 45, 'Suman': 72}

result = {
    name: 'Pass' if score >= 50 else 'Fail'
    for name, score in marks.items()
}

print(result)
# Output: {'Rahul': 'Pass', 'Amit': 'Fail', 'Suman': 'Pass'}
  

📌 কেন Dictionary Comprehension ব্যবহার করবেন?

  • কোড ছোট ও readable হয়
  • Performance ভালো
  • Less lines of code
  • Professional Python coding style

✨ Summary

Dictionary Comprehension Python-এর একটি অত্যন্ত গুরুত্বপূর্ণ feature। এটি ভালোভাবে আয়ত্ত করতে পারলে আপনার Python কোড হবে আরও clean, fast ও professional

👼 Quiz
/

লোড হচ্ছে...

Interview Questions:

1. Dictionary Comprehension কী?

এক লাইনে dictionary তৈরি করার পদ্ধতি।

2. Dictionary Comprehension এর syntax কেমন?

{key: value for item in iterable}

3. Dictionary Comprehension কোথায় উপকারী?

ডাটা transformation এ।