Informatics Practices · Ch 4 — Working with Lists and Dictionaries
Manipulating Dictionaries
Manipulating Dictionaries
Creating a dictionary is only the starting point; the real skill is applying the methods learnt in this chapter to inspect it, query it and change it. This section puts everything together — first through a set of short worked manipulations on one dictionary, and then through three complete programs that use dictionaries to solve genuine problems.
Worked manipulations on the dictionary ODD
The running example is a dictionary named ODD holding the odd numbers between 1 and 10, where each key is the decimal number and its value is that number written in words.
(a) Create the dictionary:
>>> ODD = {1:'One', 3:'Three', 5:'Five', 7:'Seven', 9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven', 9: 'Nine'}
(b) Display the keys — keys() lists every key:
>>> ODD.keys()
dict_keys([1, 3, 5, 7, 9])
(c) Display the values — values() lists every value:
>>> ODD.values()
dict_values(['One', 'Three', 'Five', 'Seven', 'Nine'])
(d) Display the items — items() gives the key-value pairs as tuples:
>>> ODD.items()
dict_items([(1, 'One'), (3, 'Three'), (5, 'Five'), (7, 'Seven'), (9, 'Nine')])
(e) Find the length — the number of pairs:
>>> len(ODD)
5
(f) and (g) Test membership — the in operator checks whether a value occurs as a key:
>>> 7 in ODD
True
>>> 2 in ODD
False
7 is one of the keys, so the test is True; 2 is not a key, so the test is False.
(h) Retrieve the value for a key — get() fetches the value paired with key 9:
>>> ODD.get(9)
'Nine'
(i) Delete an item — del with a key removes that one pair:
>>> del ODD[9]
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven'}
Program 4-4 — storing employee names and salaries
The task: accept names of employees and their salaries for a number of employees given by the user, store them in a dictionary, and display the whole record. The employee's name serves as the key and the salary as the value. The program starts from an empty dictionary created with dict(), and each pass of the loop adds one pair through plain assignment employee[name] = salary:
#Program 4-4
#Program to create a dictionary which stores names of employees
#and their salary
num = int(input("Enter the number of employees whose data to be stored: "))
employee = dict() #create an empty dictionary
for count in range(num):
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary
print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
print(k, '\t\t', employee[k])
A sample run with five employees:
Enter the number of employees to be stored: 5
Enter the name of the Employee: 'Tarun'
Enter the salary: 12000
Enter the name of the Employee: 'Amina'
Enter the salary: 34000
Enter the name of the Employee: 'Joseph'
Enter the salary: 24000
Enter the name of the Employee: 'Rahul'
Enter the salary: 30000
Enter the name of the Employee: 'Zoya'
Enter the salary: 25000
EMPLOYEE_NAME SALARY
'Tarun' 12000
'Amina' 34000
'Joseph' 24000
'Rahul' 30000
'Zoya' 25000
The final display uses the standard traversal loop: iterating over employee yields each name, and employee[k] looks up that person's salary.
Program 4-5 — counting how often each character appears in a string
The task: count the number of times every character occurs in a string entered by the user. The dictionary is the natural data structure — each distinct character becomes a key and its running count the value. The program walks through the string one character at a time: if the character is already a key, its count is increased by 1; if it is being seen for the first time, it is inserted with count 1.
#Program 4-5
#Count the number of times a character appears in a given string
st = input("Enter a string: ")
dic = {} #creates an empty dictionary
for ch in st:
if ch in dic: #if next character is already in dic
dic[ch] += 1
else:
dic[ch] = 1 #if ch appears for the first time
for key in dic:
print(key, ':', dic[key])
Sample run:
Enter a string: HelloWorld
H : 1
e : 1
l : 3
o : 2
W : 1
r : 1
d : 1
Note that the counting is case-sensitive — H and W are counted separately from any lowercase letters — and l correctly reaches 3 because it occurs three times across "Hello" and "World".
Program 4-6 — converting a number into its digit names
The task: read a number and print each of its digits in words — input 876 should produce "Eight Seven Six". Here the dictionary acts as a fixed lookup table: the keys are the digits 0 to 9 and the values are their names. The number is deliberately read as a string, so that the program can loop over it character by character; each character is converted to an integer with int(), used as a key into the table, and the retrieved name is joined onto the result string.
# Program 4-6 …