Day 29/100: Dictionary and Set Comprehensions in Python

day-29/100:-dictionary-and-set-comprehensions-in-python

Welcome to Day 29 of the 100 Days of Python series!
Yesterday, we explored list comprehensions, a concise way to create lists.
Today, we’ll dive into their powerful cousins: Dictionary and Set Comprehensions.

These are elegant Pythonic tools that help us generate dictionaries and sets from iterables in just one line of code.

🎯 What You’ll Learn

  • What dictionary comprehensions are
  • What set comprehensions are
  • Syntax and practical examples
  • When to use them
  • Common mistakes to avoid

🧾 Dictionary Comprehensions

A dictionary comprehension allows you to create dictionaries using a single line of code.

🔹 Syntax:

{key_expr: value_expr for item in iterable}

It’s the dictionary version of a list comprehension, but you specify both key and value.

✅ Example 1: Square of Numbers

squares = {x: x**2 for x in range(5)}
print(squares)
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

✅ Example 2: Character Count in a Word

word = "banana"
char_count = {char: word.count(char) for char in word}
print(char_count)
# Output: {'b': 1, 'a': 3, 'n': 2}

✅ Example 3: Swap Keys and Values

original = {'a': 1, 'b': 2, 'c': 3}
swapped = {v: k for k, v in original.items()}
print(swapped)
# Output: {1: 'a', 2: 'b', 3: 'c'}

✅ Example 4: Filtering Items

prices = {'apple': 100, 'banana': 40, 'mango': 150}
cheap_fruits = {k: v for k, v in prices.items() if v < 100}
print(cheap_fruits)
# Output: {'banana': 40}

🔁 Set Comprehensions

Set comprehensions help you generate a set using a similar syntax — great for removing duplicates automatically.

🔹 Syntax:

{expression for item in iterable}

✅ Example 1: Unique Characters

word = "balloon"
unique_chars = {char for char in word}
print(unique_chars)
# Output: {'n', 'b', 'o', 'a', 'l'}

✅ Example 2: Square of Even Numbers

even_squares = {x**2 for x in range(10) if x % 2 == 0}
print(even_squares)
# Output: {0, 4, 16, 36, 64}

💡 Why Use Them?

  • 🔄 Clean, one-line transformations
  • 🚀 Faster than traditional loops
  • 💼 Practical for filtering, transforming, or reversing data
  • Automatic uniqueness with sets

⚠️ Common Mistakes

  1. Duplicate keys in dictionary comprehensions:
    Later values will overwrite earlier ones.
   {char: i for i, char in enumerate("banana")}
   # {'b': 0, 'a': 5, 'n': 4}  # 'a' gets overwritten
  1. Forgetting .items() in dict comprehensions:
   {k: v for k, v in my_dict}  # ❌ TypeError
   {k: v for k, v in my_dict.items()}  # ✅
  1. Expecting order in sets:
    Sets are unordered; don’t rely on element positions.

🧪 Real-World Use Cases

🔧 1. Invert a Dictionary

data = {"x": 1, "y": 2}
inverted = {v: k for k, v in data.items()}
# {1: 'x', 2: 'y'}

📚 2. Create Index of Words

words = ["apple", "banana", "cherry"]
index = {word: i for i, word in enumerate(words)}
# {'apple': 0, 'banana': 1, 'cherry': 2}

🔥 3. Get All Unique Vowels in a Sentence

sentence = "Today is a beautiful day"
vowels = {char for char in sentence.lower() if char in 'aeiou'}
# {'a', 'e', 'i', 'o', 'u'}

🧭 Recap

Today you learned:

✅ How to use dictionary and set comprehensions
✅ How they differ from list comprehensions
✅ Syntax and best practices
✅ Real-world examples like inverting dictionaries and filtering data

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
podcast-|-be-prepared-for-manufacturing-growth

PODCAST | Be Prepared for Manufacturing Growth

Next Post
manufacturers-must-verify-products-are-fit-through-analysis-and-testing

Manufacturers Must Verify Products are Fit Through Analysis and Testing

Related Posts