Python · Syntax · Beginner
Sets, dictionaries, error handling
Python practice with sets, dictionaries, and error handling: unique values, common symbols, try/except, safe data handling, word grouping, and string parsing.
Quick topic start and explanations before exercises (exercises below):
Dictionary patterns — grouping and filtering
#Handling errors with try/except
#Sets, dicts, and exceptions quick reference
#Exercises:
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
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)
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)
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
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)
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
}
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
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
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
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
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
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
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
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
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