Python · Syntax · Beginner

Sets, dictionaries, error handling

15 tasks

Python practice with sets, dictionaries, and error handling: unique values, common symbols, try/except, safe data handling, word grouping, and string parsing.

Sets — uniqueness and set operations

#
A set is a collection of unique values with no guaranteed order. The defining property is uniqueness: adding the same value twice has no effect. ```python numbers = [1, 2, 2, 3, 3, 3] unique = set(numbers) print(unique) # {1, 2, 3} ``` Membership testing with in is much faster on a set than on a list, especially for large collections. This matters when you are checking thousands of items. Sets support mathematical operations: ```python a = {1, 2, 3, 4} b = {3, 4, 5, 6} print(a & b) # {3, 4} — intersection: elements in both print(a | b) # {1,2,3,4,5,6} — union: elements in either print(a - b) # {1, 2} — difference: in a but not in b ``` Finding common characters between two strings: ```python def common_chars(a, b): return set(a) & set(b) ``` set("hello") gives {"h", "e", "l", "o"} — the unique characters. The & then gives characters that appear in both strings. When to use a set instead of a list: when you need uniqueness, fast membership testing, or set operations. When order matters or you need duplicates, stick with a list.

Dictionary patterns — grouping and filtering

#
Dictionaries organize data by key instead of by position. You have already used them in OOP exercises — here the exercises work with dicts directly as function inputs and outputs. Grouping items by a property — build a dict where the key is the group and the value is a list or count: ```python def first_letter_stats(words): result = {} for word in words: letter = word[0] if letter not in result: result[letter] = [] result[letter].append(word) return result ``` Or using get with a default list — but be careful: mutable defaults are tricky. The explicit check is safer and clearer. Filtering a dict — build a new dict with only the entries that pass a condition: ```python def adults_only(data): return {name: age for name, age in data.items() if age > 18} ``` dict.items() gives you (key, value) pairs. The dict comprehension {k: v for k, v in ...} is the dict equivalent of a list comprehension. Swapping keys and values — works only when values are unique: ```python def swap_dict(d): return {v: k for k, v in d.items()} ``` Removing None values from a dict: ```python def remove_none(d): return {k: v for k, v in d.items() if v is not None} ``` Use is not None rather than != None. is tests identity, not equality — None is a singleton, so is is the correct comparison.

Handling errors with try/except

#
Exceptions are Python's way of signaling that something went wrong at runtime. int("hello") raises a ValueError. dividing by zero raises a ZeroDivisionError. Accessing a missing key raises a KeyError. Without handling these, the program crashes. try/except lets you react to an exception instead of crashing: ```python def safe_sum(text): total = 0 for part in text.split(): try: total += int(part) except ValueError: pass # skip parts that are not valid integers return total ``` The try block contains the code that might fail. If an exception of the specified type occurs, execution jumps to the except block. If no exception occurs, the except block is skipped entirely. Always catch a specific exception type rather than a bare except. Bare except catches everything — including keyboard interrupts and system exits — which makes programs hard to stop and hides real bugs. A common pattern: try to convert input, fall back to a default if conversion fails: ```python try: value = int(input("Enter a number: ")) except ValueError: value = 0 print("Not a valid number, using 0") ``` Use try/except for situations that are genuinely exceptional — invalid user input, missing files, network timeouts. Do not use it as a substitute for checking conditions you can check directly (like len(text) == 0 before accessing text[0]).

Sets, dicts, and exceptions quick reference

#
**Set operations** ```python s = {1, 2, 3} # literal s = set([1, 2, 2, 3]) # from list — duplicates removed s.add(4) # add one element s.discard(4) # remove — silent if absent 4 in s # membership test — O(1) a & b # intersection — elements in both a | b # union — elements in either a - b # difference — in a but not in b a ^ b # symmetric difference — in one but not both ``` **Dict quick reference** ```python d.get(key, default) # safe get, no KeyError d.setdefault(key, []) # set if missing, return value d.items() # (key, value) pairs d.keys() / d.values() # keys or values only # Dict comprehension {k: v for k, v in d.items() if condition} ``` **Common exceptions** | Exception | Raised when… | |---|---| | `ValueError` | right type, wrong value: `int('abc')` | | `TypeError` | wrong type: `'a' + 1` | | `KeyError` | dict key not found: `d['missing']` | | `IndexError` | list index out of range: `[][0]` | | `ZeroDivisionError` | division by zero: `1 / 0` | | `AttributeError` | no such attribute/method: `None.strip()` | | `FileNotFoundError` | file does not exist | **try / except / else / finally** ```python try: value = int(input('Number: ')) except ValueError: value = 0 # runs only when ValueError raised except (KeyError, IndexError): value = -1 # catch multiple types at once else: print('Success!') # runs only when NO exception raised finally: print('Always runs') # cleanup — always executes # Catch and inspect the exception object: except ValueError as e: print(f'Error: {e}') # Raise your own exception: raise ValueError('must be positive') ```
01

Unique positive values.

#

Write a function that takes a list of numbers and returns a set of unique positive values.

def unique_positive(nums):
    pass
Solution
def unique_positive(nums):
    result = set()
    for n in nums:
        if n > 0:
            result.add(n)
    return result
02

Common characters of two strings.

#

Write a function that takes two strings and returns a set of common characters.

def common_chars(a, b):
    pass
Solution
def common_chars(a, b):
    return set(a) & set(b)
03

Average price of products.

#

Write a function that takes a dictionary of product prices and returns the average price. If the dictionary is empty — return 0.

def average_price(prices):
    pass
Solution
def average_price(prices):
    if not prices:
        return 0
    total = 0
    for p in prices.values():
        total += p
    return total / len(prices)
04

Sum of numbers from a string.

#

Write a function that takes a string with numbers separated by spaces and returns the sum of these numbers. If a value is not a number — skip it.

def safe_sum(text):
    pass
Solution
def safe_sum(text):
    total = 0
    for part in text.split():
        try:
            total += int(part)
        except ValueError:
            pass
    return total
05

Grouping by the first letter.

#

Write a function that takes a list of words and returns a dictionary where: - key — the first letter of the word - value — the number of words starting with that letter

def first_letter_stats(words):
    pass
Solution
def first_letter_stats(words):
    result = {}
    for w in words:
        if not w:
            continue
        key = w[0]
        if key in result:
            result[key] += 1
        else:
            result[key] = 1
    return result

# or this can be done using setdefault
words = ["apple", "ant", "banana", "book"]
result = {}

for word in words:
    first = word[0]
    result.setdefault(first, []).append(word)

print(result)
06

Intersection and difference of sets.

#

Write a function that takes two sets and returns: - their intersection - their difference (first minus second)

def set_operations(a, b):
    pass
Solution
def set_operations(a, b):
    return {
        "intersection": a & b,
        "difference": a - b
    }
07

Filter older than 18.

#

Write a function that takes a dictionary {name: age} and returns a dictionary only with those who are older than 18.

def adults_only(data):
    pass
Solution
def adults_only(data):
    result = {}
    for name, age in data.items():
        if age > 18:
            result[name] = age
    return result
08

Set of value types.

#

Write a function that takes a list of values and returns a set of their types.

def value_types(values):
    pass
Solution
def value_types(values):
    result = set()
    for v in values:
        result.add(type(v))
    return result
09

Best student by score.

#

Write a function that takes a dictionary of student scores and returns the name of the student with the highest score. If the dictionary is empty — return None .

def best_student(scores):
    pass
Solution
def best_student(scores):
    if not scores:
        return None
    best = None
    max_score = -1
    for name, score in scores.items():
        if score > max_score:
            max_score = score
            best = name
    return best
10

Word counting.

#

Write a function that takes a string and returns a dictionary with the count of each word.

def word_frequency(text):
    pass
Solution
def word_frequency(text):
    result = {}
    for w in text.split():
        w = w.lower()
        if w in result:
            result[w] += 1
        else:
            result[w] = 1
    return result
11

Even and odd in a dictionary.

#

Write a function that takes a list of numbers and returns a dictionary: - "even" — count of even numbers - "odd" — count of odd numbers

def even_odd_stats(nums):
    pass
Solution
def even_odd_stats(nums):
    result = {"even": 0, "odd": 0}
    for n in nums:
        if n % 2 == 0:
            result["even"] += 1
        else:
            result["odd"] += 1
    return result
12

Removing None values.

#

Write a function that takes a dictionary and returns a new dictionary without pairs where the value is None .

def remove_none(d):
    pass
Solution
def remove_none(d):
    result = {}
    for k, v in d.items():
        if v is not None:
            result[k] = v
    return result
13

Unique words from strings.

#

Write a function that takes a list of strings and returns a set of all unique words.

def unique_words(lines):
    pass
Solution
def unique_words(lines):
    result = set()
    for line in lines:
        for w in line.split():
            result.add(w.lower())
    return result
14

Digits, letters and other characters.

#

Write a function that takes a string and returns a dictionary: - "digits" — number of digits - "letters" — number of letters - "others" — number of all other characters

def char_stats(text):
    pass
Solution
def char_stats(text):
    result = {"digits": 0, "letters": 0, "others": 0}
    for ch in text:
        if ch.isdigit():
            result["digits"] += 1
        elif ch.isalpha():
            result["letters"] += 1
        else:
            result["others"] += 1
    return result
15

Sets of words by length.

#

Write a function that takes a list of words and returns a dictionary where: - key — word length - value — set of words of that length

def group_by_length(words):
    pass
Solution
def group_by_length(words):
    result = {}
    for w in words:
        l = len(w)
        if l not in result:
            result[l] = set()
        result[l].add(w)
    return result