Решение 1. fromkeys без ловушки
keys = ["a", "b", "c"]
result = {key: [] for key in keys}
result["a"].append(1)
print(result)У каждого ключа свой список.
Решение 2. get()
user = {"name": "Alice", "age": 30}
city = user.get("city", "Unknown")
print(city)KeyError не возникает.
Решение 3. setdefault()
pairs = [("Python", "Alice"), ("Python", "Bob"), ("QA", "Eva")]
groups = {}
for group, name in pairs:
groups.setdefault(group, []).append(name)
print(groups)setdefault() создаёт список только при первом появлении группы.
Решение 4. items()
person = {"name": "Alice", "age": 30, "city": "New York"}
for key, value in person.items():
print(f"{key}: {value}")items() даёт пары без повторного обращения person[key].
Решение 5. Dict comprehension
numbers = [1, 2, 3, 4]
squares = {number: number ** 2 for number in numbers}
print(squares)Ключ - число, значение - его квадрат.
Решение 6. Распределение студентов
students = {"Аня": 92, "Боря": 76, "Ваня": 65, "Галя": 48, "Дима": 88, "Ева": 54}
groups = {
"Отличники": {},
"Хорошисты": {},
"Троечники": {},
"Не сдали": {},
}
for name, score in students.items():
if score >= 85:
groups["Отличники"][name] = score
elif score >= 70:
groups["Хорошисты"][name] = score
elif score >= 50:
groups["Троечники"][name] = score
else:
groups["Не сдали"][name] = score
print("Распределение по группам:", groups)Условия проверяются сверху вниз от самой высокой группы.