0

I'm pretty new to python, and I have a python program that is supposed to take inputs and store them into a dictionary and store that dictionary into a list, but for some reason, it's overwriting the stored dictionary in the list with the new one at each loop.

total_properties_sold = 0
total_commission = 0
bonus_pay = 0
employees = [] #empty list to store dictonary of employees information
employee = {} #empty dictonary to store the information of employees

while True:
    number_of_employees = input("Enter number of employees who have worked this week: ")
    if number_of_employees.isdigit(): #validation check to ensure input is a digit
        number_of_employees = int(number_of_employees) #if input is digit, convert to int
        if number_of_employees >= 2 and number_of_employees <= 5: #validates the range of input
            break
        else:
            print("Input invalid... enter a digit\n")
            
    else:
        print("Input invalid... enter a digit\n")
        

#for loop to enter the details of the number of employees
for number in range(number_of_employees):
    name = input("Enter employee name: ")

    while True: #validation check to ensure input is a digit
        id = input("Enter employee id: ")
        if id.isdigit():
            id = int(id)
            break
        else:    
            print("Invalid data type... enter a number\n")

    while True:
        properties_sold = input("enter number of properties sold by employee: ")
        if properties_sold.isdigit():
            properties_sold = int(properties_sold)
            break
        else: 
            print("Invalid data type... enter a number")

    total_properties_sold += properties_sold #calculates the total properties sold this week
    employee_commission = properties_sold * 500 
    employee_commission = float(employee_commission) #converts commission into a float
    total_commission += employee_commission #calculates the total commission this week
    total_commission = float(total_commission) #converts total commission into float

    #add employee information into the employee dictonary
    employee["name"] = name
    employee["employee id"] = id
    employee["properties sold"] = properties_sold
    employee["commission"] = employee_commission

    employees.append(employee) #adding the employee dictonary into employees list
    
    print(employees)

The expected output should be

[{'name': 'employee1', 'employee id': 1, 'properties sold': 4, 'commission': 2000.0}, {'name': 'employee2', 'employee id': 2, 'properties sold': 3, 'commission': 1500.0}, {'name': 'employee3', 'employee id': 3, 'properties sold': 10, 'commission': 5000.0}]

But I get:

[{'name': 'employee3', 'employee id': 3, 'properties sold': 10, 'commission': 5000.0}, {'name': 'employee3', 'employee id': 3, 'properties sold': 10, 'commission': 5000.0}, {'name': 'employee3', 'employee id': 3, 'properties sold': 10, 'commission': 5000.0}]
 
 
コリン
  • 1,005
  • 1
  • 5
  • 26
Rohail
  • 3
  • 1
  • 3
    You are appending *the same* dictionary (`employee`) multiple times, changing its contents between appends, which is why you end up with what looks like multiple copies of the *last* employee. – Scott Hunter Dec 28 '22 at 19:01
  • You can avoid appending the same instance of the dict, by appending a copy `employees.append(employee.copy())` – Andreas Dec 28 '22 at 19:07

1 Answers1

1

This is because you assign employee = {} at the beginning of the code, and it is never reassigned after that, so the code is always referring to the same object.

When you set employee["name"] = name for the next employee, you're still referring to the same employee object, and it affects the instance of employee that is already in the list.

To fix this, assign employee to a fresh dictionary at the top of the for loop:

for number in range(number_of_employees):
    employee = {}
    name = input("Enter employee name: ")

This reassigns the variable name employee to a fresh value, and breaks the connection to the previous values.

John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • I appreciate that, the code now works. if it isnt too much of a hassle could you explain to me why my first attempt didnt work. my understanding of it was during each loop the inputs for the dictionary would just overwrite the existing/previous inputs stored in the dictionary, so the newly update dictionary could be appended onto the end of the employees list. Im a CS student and still a novice at programming, would appreciate the help. – Rohail Dec 28 '22 at 19:32
  • @Rohail `employees.append(employee)` It seems like you expect this to append a _copy_ of employee to the list; but that is not what happens. _the actual object_ is appended to the list (and since this is in a loop, the object itself is appended to the list many times.) So the next time you assign `employee["name"] = name`, it affects all of the items in the list because they're all _identical references to the same object_. – John Gordon Dec 28 '22 at 19:50
  • @Rohail Other languages may not behave this way, but Python does. – John Gordon Dec 28 '22 at 19:51