মূল কন্টেন্টে যান
eLearner.app
মডিউল 6 · 2-এর পাঠ 4কোর্সে 22/36~10 min
মডিউল পাঠ (2/4)

ডিক্ট এবং বোধগম্যতা সেট করুন

The same syntax used for list comprehensions also works to build dict and set values — you just change the brackets.

Dict comprehension

Syntax: {key: value for element in iterable}.

Python
quadrati = {n: n * n for n in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Common pattern: turn a list of tuples into a dict.

Python
coppie = [("a", 1), ("b", 2), ("c", 3)]
d = {k: v for k, v in coppie}
# {'a': 1, 'b': 2, 'c': 3}
# (equivalente a dict(coppie) in questo caso)

Swap keys and values of a dict:

Python
originale = {"a": 1, "b": 2, "c": 3}
invertito = {v: k for k, v in originale.items()}
# {1: 'a', 2: 'b', 3: 'c'}

Filter a dict:

Python
prezzi = {"mela": 1.2, "pera": 1.5, "kiwi": 2.5, "ananas": 4.0}
economici = {k: v for k, v in prezzi.items() if v < 2.0}
# {'mela': 1.2, 'pera': 1.5}

Set comprehension

Syntax: {expression for element in iterable}. Same as a list comprehension, but with curly braces.

Python
parole = ["ciao", "mondo", "ciao", "python"]
uniche = {p.upper() for p in parole}
# {'CIAO', 'MONDO', 'PYTHON'}

Unique initials from a list of names:

Python
nomi = ["Ada", "Linus", "Grace", "Alan", "Guido"]
iniziali = {n[0] for n in nomi}
# {'A', 'L', 'G'}

Filter + transformation

As with list comprehensions, the trailing if filters:

Python
{n: n * n for n in range(10) if n % 2 == 0}
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Dict comprehensions for swapping keys and values

A very common pattern to invert a dictionary (swapping keys and values, assuming values are unique) is:

Python
orig_dict = {'a': 1, 'b': 2}
inv_dict = {value: key for key, value in orig_dict.items()}
# result: {1: 'a', 2: 'b'}

Try it

ব্যায়াম#python.m6.l2.e1
প্রচেষ্টা: 0লোড হচ্ছে...

Given `words = ['mela', 'pera', 'kiwi', 'banana']`, build `lengths` as a dict {word: len(word)}. Evaluate `lengths`.

সম্পাদক লোড হচ্ছে...
ইঙ্গিত দেখান

{p: len(p) for p in words}

সমাধান 3 প্রচেষ্টার পরে উপলব্ধ

Review exercise

ব্যায়াম#python.m6.l2.e2
প্রচেষ্টা: 0লোড হচ্ছে...

Given `nums = [1, 2, 2, 3, 4, 4, 5]`, build `unique_squares` as a SET of the squares. Evaluate `unique_squares`.

সম্পাদক লোড হচ্ছে...
ইঙ্গিত দেখান

Curly braces without ':' = set comprehension.

সমাধান 3 প্রচেষ্টার পরে উপলব্ধ

Additional challenge

ব্যায়াম#python.m6.l2.e3
প্রচেষ্টা: 0লোড হচ্ছে...

Given the list of strings `names = ["Alice", "Bob"]`, use a dict comprehension to create a dictionary that maps each name to its length. Store the dictionary in `name_lengths` and evaluate it.

সম্পাদক লোড হচ্ছে...
ইঙ্গিত দেখান

The syntax is {name: len(name) for name in names}.

সমাধান 3 প্রচেষ্টার পরে উপলব্ধ