Bird
0
0

Given this class:

hard📝 Application Q9 of 15
Python - Classes and Object Lifecycle
Given this class:
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

employees = [
    Employee('John', 5000),
    Employee('Jane', 6000),
    Employee('Doe', 5500)
]

How can you create a dictionary mapping employee names to their salaries using these objects?
Asalary_dict = {employees.name: employees.salary}
Bsalary_dict = {e.name: e.salary for e in employees}
Csalary_dict = dict(employees)
Dsalary_dict = {name: salary for name, salary in employees}
Step-by-Step Solution
Solution:
  1. Step 1: Understand list of Employee objects

    employees is a list of Employee instances with name and salary attributes.
  2. Step 2: Use dictionary comprehension to map names to salaries

    salary_dict = {e.name: e.salary for e in employees} correctly uses e.name and e.salary for each object e.
  3. Final Answer:

    salary_dict = {e.name: e.salary for e in employees} -> Option B
  4. Quick Check:

    Use dict comprehension with object attributes [OK]
Quick Trick: Use {obj.attr: obj.attr2 for obj in list} to create dict [OK]
Common Mistakes:
  • Trying to unpack objects directly
  • Using class name instead of object variable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes