从字典中提取值并修改它

2024-05-12 21:31:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我在学校里被这个问题困扰的时间比我想承认的要长……我已经做了5次不同的迭代来解决这个问题,我最近的一次是在这个问题下面。这是我要上的课

given the following dictionary of employees and salaries, create an personalized salary message letting each employee know they have been given a 2% raise and the new total of their salary.

expected outcome:

John, your current salary is 54000.00. You received a 2% raise. This makes your new salary 55080.0
Judy, your current salary is 71000.00. You received a 2% raise. This makes your new salary 72420.0
Albert, your current salary is 38000.00. You received a 2% raise. This makes your new salary 38760.0
Alfonzo, your current salary is 42000.00. You received a 2% raise. This makes your new salary 42840.0
employeeDatabase = {
    'John': 54000.00,
    'Judy': 71000.00,
    'Albert': 38000.00,
    'Alfonzo': 42000.00
}

我的许多尝试之一(我现在意识到我应该保存以前的尝试,我只是使用一个随机的在线IDE):

newdict = employeeDatabase.copy()

for x in newdict:
    newsal = newdict[x]
    newsal = newsal *.02 + newsal
    for i in employeeDatabase:
        print (i + ' your current salary is %s You received a 2%% raise. This makes your new salary %d'  % (employeeDatabase[i], newsal))

Tags: oftheyounewyouriscurrentthis
3条回答

您不需要在那里使用newdict,您只需使用items获取姓名和薪水,然后打印这两个值加上增加的值。我将其更改为使用新的字符串格式语法,因为旧的%样式已经不再使用:

for employee, salary in employeeDatabase.items():
        print ("{}, your current salary is {:.2f}. You received a 2% raise. This makes your new salary {:.2f}".format(employee, salary, salary * 1.02))

可以在python中使用dict对象的函数^{}。我将返回一个键值对,您可以使用for循环进行迭代。此外,通过使用字符串函数^{},您可以使用默认消息设置变量,然后在for循环中填充特定值(姓名、薪水等)

message = '{}, your current salary is {}. You received a 2% raise. This makes your new salary {}'
employeeDatabase = {
    'John': 54000.00,
    'Judy': 71000.00,
    'Albert': 38000.00,
    'Alfonzo': 42000.00
}

for employee, salary in employeeDatabase.items():
    print(message.format(employee, salary, salary * 1.02))

变量message中的{}表示要使用dict中的信息自定义默认信息的位置

由于dict结构,您可以使用键更改数据,因此:

employeeDatabase = {
    'John': 54000.00,
    'Judy': 71000.00,
    'Albert': 38000.00,
    'Alfonzo': 42000.00
}
employeeDatabase['John'] = 58000.00

现在约翰的薪水是58000英镑

要将所有员工的工资提高2%,请执行以下操作:

def raise_salary(employeers):
    for i in employeers.keys():
        print(f'{i} your current salary is {employeers[i]} You received a 2% raise. This makes your new salary {employeers[i] + employeers[i] *.02}')

注意:我使用的是f-strings,它在python3.6+上工作

相关问题 更多 >