ByteBoard Notes Notes

Create a dictionary of employee names and salaries and access them

Computer Science XI · Experiment 24 of 27 · Python

11-CSPython programs
Expt. No.24
Page No.48

Employee salary dictionary

Aim

To write a Python program that creates a dictionary of employee names and salaries, displays it, looks up one employee and raises another's salary.

Concepts used

Algorithm

  1. Input the number of employees; for each, input the name and salary and store them as key and value.
  2. Display every name with its salary.
  3. Input a name and display the salary using get(), which gives "Not found" for an unknown name.
  4. Input a name; if present, add 5000 to that salary and display it.

Program

# Dictionary of employees and their salaries emp = {}n = int(input("How many employees? "))for i in range(n):    name = input("Enter name  : ")    salary = int(input("Enter salary: "))    emp[name] = salary print("Employee details:")for name in emp:    print(name, ":", emp[name]) search = input("Whose salary do you want to see? ")print("Salary:", emp.get(search, "Not found")) name = input("Whose salary should be raised by 5000? ")if name in emp:    emp[name] = emp[name] + 5000    print("New salary of", name, ":", emp[name])else:    print(name, "is not an employee")

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python employee_salary_dictionary.py
How many employees? 3 Enter name : Ravi Enter salary: 45000 Enter name : Meena Enter salary: 52000 Enter name : Arjun Enter salary: 38000 Employee details: Ravi : 45000 Meena : 52000 Arjun : 38000 Whose salary do you want to see? Meena Salary: 52000 Whose salary should be raised by 5000? Arjun New salary of Arjun : 43000

✓ Printed by running this program, not typed by hand.

Result

The dictionary stored three employees. Meena's salary was found as 52000 with get(), and Arjun's salary was raised from 38000 to 43000 by updating its value.

Viva voce: what the examiner may ask

01What is the advantage of get() over emp[search]?

get() returns the default ("Not found") for a missing key; square brackets raise KeyError.

02How is a new item added to a dictionary?

By assigning to a new key: emp[name] = salary.

03Which methods give the keys, values and pairs?

keys(), values() and items().

Variations for the lab test

  1. Display the employee with the highest salary.
  2. Delete an employee using del or pop().
  3. Display the total salary bill using values() and sum().
! Common mistake Typing the name in different case ("meena") finds nothing, because dictionary keys are case-sensitive.
Back to the 11-CS index