這個問題在這里已經有了答案: 在 FOR 回圈中向字典添加值。更新而不是“附加” (1個答案) 16 小時前關閉。
我希望我的 pythonemployees一個一個地列印名字(在一個回圈中),讓我為amount每個員工添加薪水,最后為我創建一個字典(鍵值),key名字employee和value是amount,我也想要列印total工資金額是指所有工資的總和。我該怎么做這就是我到目前為止所做的:
employees = ["abc", "def", "ghi", "jkl", "mno", "pqr"]
n=0
amonut= 0
try:
for employee in employees:
employee = employees[n]
amount= int(input(amount))
total = sum(amount)
n=n 1
print(total)
except:
print("You can only type integer for amount")
我不知道如何在最后創建字典
uj5u.com熱心網友回復:
我的意思是……像這樣的東西?
employee_names = ["abc", "def", "ghi", "jkl", "mno", "pqr"]
employee_salaries = {}
for employee in employee_names:
while True: # Input validation loop
try:
employee_salaries[employee] = int(input(f"Enter {employee}'s salary: "))
break
except ValueError:
print("Invalid input")
print(employee_salaries)
total = sum(employee_salaries.values())
print(total)
uj5u.com熱心網友回復:
employees = ["abc", "def", "ghi", "jkl", "mno", "pqr"]
salary={}
for emp in employees:
try:
amount=int(input(f'Enter salary for {emp}: '))
salary[emp]=amount
except ValueError:
print(f'Wrong salary input for {emp} ')
print(salary)
print('Total salary ',sum(salary.values()))
uj5u.com熱心網友回復:
這里不需要n變數。您可以創建字典并添加員工和金額
employees = ["abc", "def", "ghi", "jkl", "mno", "pqr"]
employees_dictionary = dict()
total = 0
amount = 0
try:
for employee in employees:
amount= int(input(amount))
employees_dictionary[employee] = amount
total = amount
except:
print("You can only type integer for amount")
print(employees_dictionary)
print(total)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/430279.html
標籤:Python python-3.x 列表 字典
上一篇:有條件的字典串列到一個字典中
