0% found this document useful (0 votes)
20 views

10 Tuples and dictionary (1)

Uploaded by

ujspucprincipal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

10 Tuples and dictionary (1)

Uploaded by

ujspucprincipal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

Chapter 10 Tuples and Dictionary

INTRODUCTION TO TUPLES
 A tuple is an ordered sequence of elements of different data types, such as integer, float, string, list or even a tuple.
 Elements of a tuple are enclosed in parenthesis (round brackets) and are separated by commas.
 Like list and string, elements of a tuple can be accessed using index values, starting from 0.

Example 1:
>>> tuple1 = (1,2,3,4,5) #tuple1 is the tuple of integers
>>> tuple1
(1, 2, 3, 4, 5)
Example 2:
>>> tuple2 =('Economics',87,'Accountancy',89.6) #tuple2 is the tuple of mixed data types
>>> tuple2
('Economics', 87, 'Accountancy', 89.6)
Example 3:
>>> tuple3 = (10,20,30,[40,50]) #tuple3 is the tuple with list as an element
>>> tuple3
(10, 20, 30, [40, 50])
Example 4:
>>> tuple4 = (1,2,3,4,5,(10,20)) #tuple4 is the tuple with tuple as an element
>>> tuple4
(1, 2, 3, 4, 5, (10, 20))
Note
 If there is only a single element in a tuple then the element should be followed by a comma.
 If we assign the value without comma it is treated as integer.
 It should be noted that a sequence without parenthesis is treated as tuple by default.

Example 1:
 Incorrect way of assigning single element to tuple.
 Tuple5 is assigned a single element
>>> tuple5 = (20)
>>> tuple5
20
Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 1
I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

>>>type(tuple5) #tuple5 is not of type tuple


<class 'int'> #it is treated as integer

Example 2:
 Correct Way of assigning single element to tuple.
 tuple5 is assigned a single element

>>> tuple5 = (20,) #element followed by comma


>>> tuple5
(20,)
>>>type(tuple5) #tuple5 is of type tuple
<class 'tuple'>

Example 3: a sequence without parentheses is treated as tuple by default

>>> seq = 1,2,3 #comma separated elements


>>> type(seq) #treated as tuple
<class 'tuple'>

>>> print(seq) #seq is a tuple


(1, 2, 3)

Accessing Elements in a Tuple: Elements of a tuple can be accessed in the same way as a list or string using indexing and slicing.
Example 1:
>>> tuple1 = (2,4,6,8,10,12)
#initializes a tuple tuple1
#returns the first element of tuple1
>>> tuple1[0]
2
Example 2:
#returns fourth element of tuple1
>>> tuple1[3]
8

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 2


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

Example 3: #returns error as index is out of range


>>> tuple1[15]
IndexError: tuple index out of range

Example 4: #an expression resulting in an integer index


>>> tuple1[1+4]
12

Example 5: #returns first element from right


>>> tuple1[-1]
12

Tuple is Immutable
 Tuple is an immutable data type.
 It means that the elements of a tuple cannot be changed after it has been created.
 An attempt to do this would lead to an error.
Example 1:
>>> tuple1 = (1,2,3,4,5)
>>> tuple1[4] = 10
TypeError: 'tuple' object does not support item assignment

But an element of a tuple may be of mutable type, if there is a list.


>>> tuple2 = (1,2,3,[8,9]) #4th element of the tuple2 is a list
>>> tuple2[3][1] = 10 #modify the list element of the tuple tuple2
>>> tuple2 #modification is reflected in tuple2
(1, 2, 3, [8, 10])

TUPLE OPERATIONS
1) Concatenation
2) Repetition
3) Membership
4) Slicing

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 3


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

1) Concatenation
 Python allows to join tuples using concatenation operator plus, represented by symbol +.
 It is also possible create a new tuple which contains the result of this concatenation operation.

Example 1:
>>> tuple1 = (1,3,5,7,9)
>>> tuple2 = (2,4,6,8,10)
>>> tuple1 + tuple2
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10) #concatenates two tuples

Example 2:
>>> tuple3 = ('Red','Green','Blue')
>>> tuple4 = ('Cyan', 'Magenta', 'Yellow','Black')
>>> tuple5 = tuple3 + tuple4
>>> tuple5 #tuple5 stores elements of tuple3 and tuple4
('Red','Green','Blue','Cyan','Magenta','Yellow','Black')

Extending tuple
 Concatenation operator can also be used for extending an existing tuple.
 When tuple is extended, using concatenation a new tuple is created.

Example 1:
>>> tuple6 = (1,2,3,4,5)
>>> tuple6 = tuple6 + (6,) #single element is appended to tuple6
>>> tuple6
(1, 2, 3, 4, 5, 6)
Example 2: more than one elements are appended
>>> tuple6 = (1,2,3,4,5)
>>> tuple6 = tuple6 + (7,8,9)
>>> tuple6
(1, 2, 3, 4, 5, 6, 7, 8, 9)

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 4


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

2) Repetition
Repetition operation is represented by the symbol *.
It is used to repeat elements of a tuple.
The repetition operator requires the first operand to be a tuple and the second operand to be an integer only.
Example 1:
>>> tuple1 = ('Hello','World')
>>> tuple1 * 3
('Hello', 'World', 'Hello', 'World', 'Hello', 'World')

Example 2: tuple with single element


>>> tuple2 = ("Hello",)
>>> tuple2 * 4
('Hello', 'Hello', 'Hello', 'Hello')

3) Membership:
 The in operator checks if the element is present in the tuple and returns True, else it returns False.
 The not in operator returns True if the element is not present in the tuple, else it returns False.

Example 1:
>>> tuple1 = ('Red','Green','Blue')
>>> 'Green' in tuple1
True

Example 2:
>>> tuple1 = ('Red','Green','Blue')
>>> 'Green' not in tuple1
False

4) Slicing: In Python, to access some part of a tuple, a method called slicing is used.
Example 1:
>>> tuple1 = (10,20,30,40,50,60,70,80)
>>> tuple1[2:7] #elements from index 2 to index 6
(30, 40, 50, 60, 70)

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 5


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

Example 2: all elements of tuple are printed


>>> tuple1 = (10,20,30,40,50,60,70,80)
>>> tuple1[0:len(tuple1)]
(10, 20, 30, 40, 50, 60, 70, 80)

Example 3: slice starts from zero index


>>> tuple1 = (10,20,30,40,50,60,70,80)
>>> tuple1[:5]
(10, 20, 30, 40, 50)

Example 4: slice is till end of the tuple


>>> tuple1[2:]
(30, 40, 50, 60, 70, 80)

Example 5: Using step size 2


>>> tuple1 = (10,20,30,40,50,60,70,80)
>>> tuple1[0:len(tuple1):2]
(10, 30, 50, 70)

Example 6: Negative indexing


>>> tuple1[-6:-4]
(30, 40)

Example 7: tuple is traversed in reverse order


>>> tuple1[::-1]
(80, 70, 60, 50, 40, 30, 20, 10)

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 6


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

TUPLE METHODS AND BUILT-IN FUNCTIONS: Following is a list of some of the commonly used tuple methods and built-in functions.

1) len(): Returns the length or the number of elements of the tuple passed as the argument
Example 1:
>>> tuple1 = (10,20,30,40,50)
>>> len(tuple1)
5

2) tuple()
 Creates an empty tuple if no argument is passed
 Creates a tuple if a sequence is passed as argument

Example 1:
>>> tuple1 = tuple()
>>> tuple1
()

Example 2:
>>> tuple1 = tuple('aeiou') #string
>>> tuple1
('a', 'e', 'i', 'o', 'u')
Example 3:
>>> tuple2 = tuple([1,2,3]) #list
>>> tuple2
(1, 2, 3)
Example 4:
>>> tuple3 = tuple(range(5))
>>> tuple3
(0, 1, 2, 3, 4)

3) count (): Returns the number of times the given element appears in the tuple.

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 7


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

Example 1:
>>> tuple1 = (10,20,30,10,40,10,50)
>>> tuple1.count(10)
3
Example 2:
>>> tuple1 = (10,20,30,10,40,10,50)
>>> tuple1.count(90)
0

4) index(): Returns the index of the first occurrence of the element in the given tuple.
Example 1:
>>> tuple1 = (10,20,30,40,50)
>>> tuple1.index(30)
2
Example 2:
>>> tuple1 = (10,20,30,40,50)
>>> tuple1.index(90)
ValueError: tuple.index(x): x not in tuple

5) sorted():
 Takes elements in the tuple and returns a new sorted list.
 sorted() does not make any change to the original tuple
Example:
>>> tuple1 = ("Rama","Heena","Raj","Mohsin","Aditya")
>>> sorted(tuple1)
['Aditya', 'Heena', 'Mohsin', 'Raj','Rama']

6) min(): Returns minimum or smallest element of the tuple


Example :
>>> tuple1 = (19,12,56,18,9,87,34)
>>> min(tuple1)
9

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 8


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

7) max(): Returns maximum or largest element of the tuple


Example:
>>> tuple1 = (19,12,56,18,9,87,34)
>>> max(tuple1)
87

8) sum(): Returns sum of the elements of the Tuple


Example:
>>> tuple1 = (19,12,56,18,9,87,34)
>>> sum(tuple1)
235

TUPLE ASSIGNMENT
 It allows a tuple of variables on the left side of the assignment operator to be assigned respective values from a tuple on the right
side.
 The number of variables on the left should be same as the number of elements in the tuple.
 If there is an expression on the right side then the expression is evaluated first and result is assigned to the tuple.

Example 1: The first element 10 is assigned to num1 and the second element 20 is assigned to num2.
>>> (num1,num2) = (10,20)
>>> print(num1)
10
>>> print(num2)
20
Example 2:
>>> record = ( "Pooja",40,"CS")
>>> (name,rollNo,subject) = record
>>> name
'Pooja'
>>> rollNo
40
>>> subject
'CS'

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 9


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

Example 3:
>>> (a,b,c,d) = (5,6,8)
ValueError: not enough values to unpack
(expected 4, got 3)

Example 4: 15 is assigned to num3 and 25 is assigned to num4


>>> (num3,num4) = (10+5,20+5)
>>> print(num3)
15
>>> print(num4)
25

NESTED TUPLES: A tuple inside another tuple is called a nested tuple.

Program: In the following program roll number, name and marks (in percentage) of students are saved in a tuple. To store details of many
such students, nested tuple is created.

Program:
st=((101,"Aman",98),(102,"Geet",95),(103,"Sahil",87),(104,"Pawan",79))
print("S_No"," Roll_No"," Name"," Marks")
for i in range(0,len(st)):
print((i+1),'\t',st[i][0],'\t',st[i][1],'\t',st[i][2])

Output:
S_No Roll_No Name Marks
1 101 Aman 98
2 102 Geet 95
3 103 Sahil 87
4 104 Pawan 79

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 10


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

TUPLE HANDLING
Program 1: Write a program to swap two numbers without using a temporary variable.
Program:
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print("\nNumbers before swapping:")
print("First Number:",num1)
print("Second Number:",num2)
(num1,num2) = (num2,num1)
print("\nNumbers after swapping:")
print("Second Number:",num2)

Output:
Enter the first number: 5
Enter the second number: 10

Numbers before swapping:


First Number: 5
Second Number: 10

Numbers after swapping:


First Number: 10
Second Number: 5

Program 2: Write a program to compute the area and circumference of a circle using a function.
Program:
def circle(r):
area = 3.14*r*r
circumference = 2*3.14*r
return (area,circumference)

radius = int(input('Enter radius of circle: '))


area,circumference = circle(radius)
print('Area of circle is:',area)

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 11


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

print('Circumference of circle is:',circumference)


Output:
Enter radius of circle: 5
Area of circle is: 78.5
Circumference of circle is: 31.400000000000002

Program 3: Write a program to input n numbers from the user. Store these numbers in a tuple. Print the maximum and minimum number
from this tuple.
Program:
numbers = tuple() #create an empty tuple 'numbers'
n = int(input("How many numbers you want to enter?: "))
for i in range(0,n):
num = int(input())
numbers = numbers +(num,)

print('\nThe numbers in the tuple are:')


print(numbers)
print("\nThe maximum number is:")
print(max(numbers))
print("The minimum number is:")
print(min(numbers))

Output:
How many numbers do you want to enter?: 5
98
10
12
15

The numbers in the tuple are:


(9, 8, 10, 12, 15)

The maximum number is:


15

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 12


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

The minimum number is:


8

INTRODUCTION TO DICTIONARIES
 The data type dictionary fall under mapping.
 It is a mapping between a set of keys and a set of values.
 The key-value pair is called an item.
 A key is separated from its value by a colon(:) and consecutive items are separated by commas.
 Items in dictionaries are unordered, so it may not be possible to get back the data in the same order in which it is entered initially in
the dictionary.

Creating a Dictionary
 To create a dictionary, the items entered are separated by commas and enclosed in curly braces.
 Each item is a key value pair, separated through colon (:).
 The keys in the dictionary must be unique and should be of any immutable data type, i.e., number, string or tuple.
 The values can be repeated and can be of any data type.

Example 1:
 dict1 is an empty Dictionary created
 curly braces are used for dictionary
>>> dict1 = { }
>>> dict1
{}

Example 2: dict2 is an empty dictionary created using built-in function.


>>> dict2 = dict()
>>> dict2
{}
Example 3: dict3 is the dictionary that maps names of the students to respective marks in percentage
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict3
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85}

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 13


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

Accessing Items in a Dictionary


 The items of a dictionary are accessed via the keys rather than via their relative positions or indices.
 Each key serves as the index and maps to a value.

Example: The following code shows how a dictionary returns the value corresponding to the given key:
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict3['Ram']
89
>>> dict3['Sangeeta']
85
Example 2: If the key does not exist , an error is generated.
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict3['Shyam']
KeyError: 'Shyam'

DICTIONARIES ARE MUTABLE: Dictionaries are mutable which implies that the contents of the dictionary can be changed after it has been
created.
Example 1: Adding a new item to the dictionary as shown in the following example:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85, 'Meena': 78}

Example 2: The existing dictionary can be modified by just overwriting the key-value pair.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict1['Suhel'] = 93.5
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 93.5,'Sangeeta': 85}

DICTIONARY OPERATIONS
1) Membership
 The membership operator in checks if the key is present in the dictionary and returns True, else it returns False.
 The not in operator returns True if the key is not present in the dictionary, else it returns False.

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 14


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

Example 1:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> 'Suhel' in dict1
True
Example 2:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> 'Suhel' not in dict1
False

TRAVERSING A DICTIONARY: for loop is used to access each item of the dictionary or traverse a dictionary.
Example: Consider a dictionary
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}

Method 1:
>>> for key in dict1:
print(key,':',dict1[key])

Output:
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85

Method 2
>>> for key,value in dict1.items():
print(key,':',value)
Output:
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 15


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

DICTIONARY METHODS AND BUILT-IN FUNCTIONS: Some of the commonly used dictionary methods and built-in functions are listed
below.

1) len(): Returns the length or number of key: value pairs of the dictionary passed as the argument.
Example 1:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> len(dict1)
4

2) dict(): Creates a dictionary from a sequence of key-value pairs


Example:
pair1 = [('Mohan',95),('Ram',89),('Suhel',92),('Sangeeta',85)]
>>> pair1
[('Mohan', 95), ('Ram', 89), ('Suhel',92), ('Sangeeta', 85)]
>>> dict1 = dict(pair1)
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85}

3) keys(): Returns a list of keys in the dictionary


>>> dict1 = {'Mohan':95, 'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict1.keys()
dict_keys(['Mohan', 'Ram', 'Suhel','Sangeeta'])

4) values(): Returns a list of values in the dictionary


Example:
>>> dict1 = {'Mohan':95, 'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict1.values()
dict_values([95, 89, 92, 85])

5) items(): Returns a list of tuples(key – value) pair


Example:
>>> dict1 = {'Mohan':95, 'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict1.items()
dict_items([( 'Mohan', 95), ('Ram',89), ('Suhel', 92), ('Sangeeta', 85)])

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 16


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

6) get():
 Returns the value corresponding to the key passed as the argument
 If the key is not present in the dictionary it will return None
Example:
>>> dict1 = {'Mohan':95, 'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict1.get('Sangeeta')
85
>>> dict1.get('Sohan')
>>>

7) update(): appends the key-value pair of the dictionary passed as the argument to the key-value pair of the given dictionary
Example:
>>> dict1 = {'Mohan':95, 'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict2 = {'Sohan':79,'Geeta':89}
>>> dict1.update(dict2)
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85, 'Sohan': 79, 'Geeta':89}
>>> dict2
{'Sohan': 79, 'Geeta': 89}

8) del():
 Deletes the item with the given key.
 To delete the dictionary from the memory we write: del Dict_name
Example:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> del dict1['Ram']
>>> dict1
{'Mohan':95,'Suhel':92, 'Sangeeta': 85}
>>> del dict1 ['Mohan']
>>> dict1
{'Suhel': 92, 'Sangeeta': 85}
>>> del dict1
>>> dict1

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 17


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

NameError: name 'dict1' is not defined

9) clear() Deletes or clear all the items of the dictionary


Example:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict1.clear()
>>> dict1
{}

MANIPULATING DICTIONARIES: The following programs show the application of manipulation methods, functions on dictionaries.

Program: Create a dictionary ‘ODD’ of odd numbers between 1 and 10, where the key is the decimal number and the value is the
corresponding number in words. Perform the following operations on this dictionary:
(a) Display the keys
(b) Display the values
(c) Display the items
(d) Find the length of the dictionary
(e) Check if 7 is present or not
(f) Check if 2 is present or not
(g) Retrieve the value corresponding to the key 9
(h) Delete the item from the dictionary corresponding to the key 9
Program:
>>> ODD = {1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven', 9: 'Nine'}

(a) Display the keys


>>> ODD.keys()
dict_keys([1, 3, 5, 7, 9])

(b) Display the values


>>> ODD.values()
dict_values(['One', 'Three', 'Five', 'Seven', 'Nine'])

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 18


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

(c) Display the items


>>> ODD.items()
dict_items([(1, 'One'), (3, 'Three'), (5, 'Five'), (7, 'Seven'),(9, 'Nine')])

(d) Find the length of the dictionary


>>> len(ODD)
5

(e) Check if 7 is present or not


>>> 7 in ODD
True

(f) Check if 2 is present or not


>>> 2 in ODD
False

(g) Retrieve the value corresponding to the key 9


>>> ODD.get(9)
'Nine'

(h) Delete the item from the dictionary corresponding to the key 9
>>> del ODD[9]
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven'}

Program: Write a program to enter names of employees and their salaries as input and store them in a dictionary.
Program:
num = int(input("Enter the number of employees whose data to be stored: "))
count = 1
employee = dict() #create an empty dictionary
while count <= num:
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 19


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

count += 1
print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
print(k,'\t\t',employee[k])
Output:
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

Program: Write a program to count the number of times a character appears in a given string.
Program:
st = input("Enter a string: ")
dic = {} #creates an empty dictionary
for ch in st:
if ch in dic: #if next character is already in the dictionary
dic[ch] += 1
else:
dic[ch] = 1 #if ch appears for the first time
for key in dic:
print(key,':',dic[key])

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 20


I PUC 2024-25 (New syllabus) Computer Science Chapter 10 Tuples and Dictionary

Output:
Enter a string: HelloWorld
H:1
e:1
l:3
o:2
W:1
r:1
d:1

Program: Write a function to convert a number entered by the user into its corresponding number in words. For example, if the input is
876 then the output should be ‘Eight Seven Six’.
Program:
def convert(num):
numberNames = {0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',\5:'Five',6:'Six',7:'Seven',8:'Eight',9:'Nine'}
result = ''
for ch in num:
key = int(ch) #converts character to integer
value = numberNames[key]
result = result + ' ' + value
return result
num = input("Enter any number: ") #number is stored as string
result = convert(num)
print("The number is:",num)
print("The numberName is:",result)

Output:
Enter any number: 6512
The number is: 6512
The numberName is: Six Five One Two

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 21

You might also like