You are on page 1of 17

SBOA SCHOOL AND JUNIOR COLLEGE, CHENNAI – 101

Std: XI Computer Science – Dictionary in python

Question 1:
Write programs to sort the dictionary {'ravi': '10', 'rajnish': '9', 'sanjeev': '15',
'yash': '2', 'suraj': '32'} and print

ANSWER:
dict = {'ravi': '10', 'rajnish': '9', 'sanjeev': '15', 'yash':
'2', 'suraj': '32'}

# sorting and printing with keys - names


for i in sorted(dict):
print((i, dict[i]), sep="\n ")

# sorting and printing with values - numbers


dict1=sorted(dict.values())
print(dict1)

# sorting and printing with keys pair - both


dict2 = sorted(dict.items())
print(dict2)

OUTPUT:

('rajnish', '9')
('ravi', '10')
('sanjeev', '15')
('suraj', '32')
('yash', '2')

['10', '15', '2', '32', '9']

[('rajnish', '9'), ('ravi', '10'), ('sanjeev', '15'), ('suraj', '32'), ('yash', '2')]
SBOA SCHOOL AND JUNIOR COLLEGE, CHENNAI – 101

Std: XI Computer Science – Dictionary in python


Question 2:

Write a Python program to find the highest 2 values in a dictionary.


ANSWER:

#Defining a dictionary
dic =
{"A":12,"B":13,"C":9,"D":89,"E":34,"F":17,"G":65,"H":36,"I":25,"J
":11}

#Creating an empty list to store all the values of the dictionary


lst = list()

#Looping through each values and storing it in list


for a in dic.values():
lst.append(a)

#Sorting the list in ascending order, it will store the highest


value at the last index
lst.sort()

#Printing the highest and second highest value using negative


indexing of the list
print("Highest value:",lst[-1])
print("Second highest value:",lst[-2])

OUTPUT:
Highest value: 89
Second highest value: 65

Question 3

Write a Python program to create a dictionary from a string.


Note: Track the count of the letters from the string.

Sample string : 'w3resource'


Expected output : {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}
ANSWER:

st = input("Enter a string: ")

dic = {}
SBOA SCHOOL AND JUNIOR COLLEGE, CHENNAI – 101

Std: XI Computer Science – Dictionary in python


#creates an empty dictionary

for ch in st:
if ch in dic:
#if next character is already in the dictionary
dic[ch] += 1
else:
#if ch appears for the first time
dic[ch] = 1

#Printing the count of characters in the string


print(dic)

OUTPUT:
Enter a string: meritnation
{'m': 1, 'e': 1, 'r': 1, 'i': 2, 't': 2, 'n': 2, 'a': 1, 'o': 1}

Question 4:
write a program to enter names of employees and their salaries as input
and store them in a dictionary. Here n is to input by the user.
ANSWER:
#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: "))
count = 1
# Create an empty dictionary
employee = dict()

# Entering data
for count in range (num):
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary

# Displaying data
SBOA SCHOOL AND JUNIOR COLLEGE, CHENNAI – 101

Std: XI Computer Science – Dictionary in python


print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
print(k,'\t\t',employee[k])

OUTPUT:

Enter the number of employees whose data to be stored: 5


Enter the name of the Employee: Gomathi
Enter the salary: 55000
Enter the name of the Employee: Rohith
Enter the salary: 65000
Enter the name of the Employee: Suraj
Enter the salary: 65000
Enter the name of the Employee: Moveen
Enter the salary: 65000
Enter the name of the Employee: Anusri
Enter the salary: 65000

EMPLOYEE_NAME SALARY
Gomathi 55000
Rohith 65000
Suraj 65000
Moveen 65000
Anusri 65000

Question 5:
Write a program to count the number of times a character appears in a given string
ANSWER:
#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
# Display keys
SBOA SCHOOL AND JUNIOR COLLEGE, CHENNAI – 101

Std: XI Computer Science – Dictionary in python


for key in dic:
print(key,':',dic[key])

OUTPUT:
Enter a string: SBOAJC SCHOOL
S:2
B:1
O:3
A:1
J:1
C:2
H: 1
L:1

Question 6:
Write a program 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’.
ANSWER:
#number is stored as string
num = input("Enter any number: ")
#numberNames is a dictionary of digits and corresponding number
#names
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

print("The number is:",num)


print("The numberName is:",result)
SBOA SCHOOL AND JUNIOR COLLEGE, CHENNAI – 101

Std: XI Computer Science – Dictionary in python


OUTPUT:
Enter any number: 786
The number is: 786
The numberName is: Seven Eight Six

num = int(input("Enter a number: "))


d = {0 : "Zero" , 1 : "One" , 2 : "Two" , 3 : "Three" , 4 : "Four" , 5 : "Five" , 6 : "Six" , 7 : "Seven"
, 8 : "Eight" , 9 : "Nine"}
digit = 0
str = "" ALTERNATE
while num > 0:
digit = num % 10
PROGRAM
num = num // 10
str = d[digit] + " " + str

print(str)

Question 7:
Repeatedly ask the user to enter a team name and how many games the team has
won and how many they lost. Store this information in a dictionary where the keys
are the team names and the values are lists of the form [wins, losses].

(a) Using the dictionary created above, allow the user to enter a team name and
print out the team's winning percentage.

(b) Using the dictionary, create a list whose entries are the number of wins of each
team.

(c) Using the dictionary, create a list of all those teams that have winning records.

ANSWER:
d = {}
ans = "y"
while ans == "y" or ans == "Y" :
name = input("Enter Team name: ")
SBOA SCHOOL AND JUNIOR COLLEGE, CHENNAI – 101

Std: XI Computer Science – Dictionary in python


w = int(input("Enter number of wins: "))
l = int(input("Enter number of losses: "))
d[name] = [w, l]
ans = input("Do you want to enter more team names? (y/n):
")

team = input("Enter team name for winning percentage: ")


if team not in d:
print("Team not found", team)
else:
wp = d[team][0] / sum(d[team]) * 100
print("Winning percentage of", team, "is", wp)

w_team = []
for i in d.values():
w_team.append(i[0])

print("Number of wins of each team", w_team)

w_rec = []
for i in d:
if d[i][0] > 0:
w_rec.append(i)

print("Teams having winning records are:", w_rec)

Output

Enter Team name: masters


Enter number of wins: 9
Enter number of losses: 1
Do you want to enter more team names? (y/n): y
Enter Team name: musketeers
Enter number of wins: 6
Enter number of losses: 4
Do you want to enter more team names? (y/n): y
Enter Team name: challengers
Enter number of wins: 0
Enter number of losses: 10
Do you want to enter more team names? (y/n): n
Enter team name for winning percentage: musketeers

Winning percentage of musketeers is 60.0


Number of wins of each team [9, 6, 0]
Teams having winning records are: ['masters', 'musketeers']
SBOA SCHOOL AND JUNIOR COLLEGE, CHENNAI – 101

Std: XI Computer Science – Dictionary in python


Question 8

Write a program that repeatedly asks the user to enter product names and prices.
Store all of these in a dictionary whose keys are the product names and whose
values are the prices.

When the user is done entering products and prices, allow them to repeatedly enter
a product name and print the corresponding price or a message if the product is not
in the dictionary.

ANSWER

d = {}
ans = "y"
while ans == "y" or ans == "Y" :
p_name = input("Enter the product name: ")
p_price = float(input("Enter product price: "))
d[p_name] = p_price
ans = input("Do you want to enter more product names? (y/n): ")

ans = "y"
while ans == "y" or ans == "Y" :
p_name = input("Enter the product name to search: ")
print("Price:", d.get(p_name, "Product not found"))
ans = input("Do you want to know price of more products? (y/n):
")

Output

Enter the product name: apple


Enter product price: 165.76
Do you want to enter more product names? (y/n): y
Enter the product name: banana
Enter product price: 75
Do you want to enter more product names? (y/n): y
Enter the product name: guava
Enter product price: 48.5
Do you want to enter more product names? (y/n): n
Enter the product name to search: apple
Price: 165.76
Do you want to know price of more products? (y/n): y
Enter the product name to search: tomato
Price: Product not found
Do you want to know price of more products? (y/n): n
SBOA SCHOOL AND JUNIOR COLLEGE, CHENNAI – 101

Std: XI Computer Science – Dictionary in python


Question 9

Create a dictionary whose keys are month names and whose values are the number of days in
the corresponding months.

(a) Ask the user to enter a month name and use the dictionary to tell how many days are in the
month.

(b) Print out all of the keys in alphabetical order.

(c) Print out all of the months with 31 days.

(d) Print out the (key-value) pairs sorted by the number of days in each month.

ANSWER

days_in_months = {
"january":31,
"february":28,
"march":31,
"april":30,
"may":31,
"june":30,
"july":31,
"august":31,
"september":30,
"october":31,
"november":30,
"december":31
}

m = input("Enter name of month: ")

if m not in days_in_months:
print("Please enter the correct month")
else:
print("There are", days_in_months[m], "days in", m)

print("Months in alphabetical order are:", sorted(days_in_months))

print("Months with 31 days:", end=" ")


for i in days_in_months:
if days_in_months[i] == 31:
print(i, end=" ")

day_month_lst = []
for i in days_in_months:
day_month_lst.append([days_in_months[i], i])
day_month_lst.sort()
SBOA SCHOOL AND JUNIOR COLLEGE, CHENNAI – 101

Std: XI Computer Science – Dictionary in python


month_day_lst =[]
for i in day_month_lst:
month_day_lst.append([i[1], i[0]])

sorted_days_in_months = dict(month_day_lst)
print()
print("Months sorted by days:", sorted_days_in_months)

Output

Enter name of month: may


There are 31 days in may
Months in alphabetical order are: ['april', 'august', 'december',
'february', 'january', 'july', 'june', 'march', 'may', 'november',
'october', 'september']
Months with 31 days: january march may july august october december
Months sorted by days: {'february': 28, 'april': 30, 'june': 30,
'november': 30, 'september': 30, 'august': 31, 'december': 31,
'january': 31, 'july': 31, 'march': 31, 'may': 31, 'october': 31}

Question 10

Can you store the details of 10 students in a dictionary at the same time ? Details
include - rollno, name, marks, grade etc. Give example to support your answer.

ANSWER

n = 10
details = {}

for i in range(n):
name = input("Enter the name of student: ")
roll_num = int(input("Enter the roll number of student: "))
marks = int(input("Enter the marks of student: "))
grade = input("Enter the grade of student: ")
details[roll_num] = [name, marks, grade]
print()
print(details)

Output

Enter the name of student: Sushma


Enter the roll number of student: 4
Enter the marks of student: 56
Enter the grade of student: C

Enter the name of student: Radhika


Enter the roll number of student: 3
SBOA SCHOOL AND JUNIOR COLLEGE, CHENNAI – 101

Std: XI Computer Science – Dictionary in python


Enter the marks of student: 90
Enter the grade of student: A+

Enter the name of student: Manika


Enter the roll number of student: 45
Enter the marks of student: 45
Enter the grade of student: D

Enter the name of student: Mitanshu


Enter the roll number of student: 1
Enter the marks of student: 23
Enter the grade of student: F

Enter the name of student: Anshika


Enter the roll number of student: 7
Enter the marks of student: 77
Enter the grade of student: B

Enter the name of student: Purva


Enter the roll number of student: 9
Enter the marks of student: 99
Enter the grade of student: A+

Enter the name of student: Sanjana


Enter the roll number of student: 3
Enter the marks of student: 76
Enter the grade of student: B+

Enter the name of student: Priyanka


Enter the roll number of student: 2
Enter the marks of student: 89
Enter the grade of student: A

Enter the name of student: Anand


Enter the roll number of student: 6
Enter the marks of student: 100
Enter the grade of student: A+

Enter the name of student: Sarika


Enter the roll number of student: 10
Enter the marks of student: 55
Enter the grade of student: B+

{4: ['Sushma', 56, 'C'], 3: ['Sanjana', 76, 'B+'], 45:


['Manika', 45, 'D'], 1: ['Mitanshu', 23, 'F'], 7:
['Anshika', 77, 'B'], 9: ['Purva', 99, 'A+'], 2:
['Priyanka', 89, 'A'], 6: ['Anand', 100, 'A+'], 10:
['Sarika', 55, 'B+']}
SBOA SCHOOL AND JUNIOR COLLEGE, CHENNAI – 101

Std: XI Computer Science – Dictionary in python


Question 11
Given the dictionary x = {'k1':'v1', 'k2':'v2', 'k3':'v3'}, create a dictionary with the opposite
mapping, i.e., write a program to create the dictionary as :
inverted_x = {'v1': 'k1' , 'v2' :'k2' , 'v3':'k3'}

ANSWER

x = { "k1" : "v1" , "k2" : "v2", "k3" : "v3"}


inverted_x = {}
for i in x :
inverted_x[x[i]] = i
print(inverted_x)

Output

{'v1': 'k1', 'v2': 'k2', 'v3': 'k3'}

Question 12

Given two dictionaries say D1 and D2. Write a program that lists the overlapping keys of
the two dictionaries, i.e., if a key of D1 is also a key of D2, then list it.

ANSWER

d1 = eval(input("Enter first dictionary: "))


d2 = eval(input("Enter second dictionary: "))

print("First dictionary: ", d1)


print("Second dictionary: ", d2)

if len(d1) > len(d2):


longDict = d1
shortDict = d2
else:
longDict = d2
shortDict = d1

print("overlapping keys in the two dictionaries are:", end=' ')


for i in shortDict:
if i in longDict:
print(i, end=' ')

Output

Enter first dictionary: {'a': 1, 'b':2, 'c': 3, 'd': 4}


Enter second dictionary: {'c': 3, 'd': 4, 'e': 5}
First dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
SBOA SCHOOL AND JUNIOR COLLEGE, CHENNAI – 101

Std: XI Computer Science – Dictionary in python


Second dictionary: {'c': 3, 'd': 4, 'e': 5}
overlapping keys in the two dictionaries are: c d

Question 13

Write a program that checks if two same values in a dictionary have different keys.
That is, for dictionary D1 = { 'a' : 10, 'b': 20, 'c' : 10}, the program should print 2 keys
have same values and for dictionary D2 = {'a' : 10, 'b' : 20, 'c' : 30} , the program
should print No keys have same values.

ANSWER

D1 = eval(input("Enter a dictionary D1: "))


print("D1 =", D1)

val = tuple(D1.values())
seen = []
flag = True

for i in val:
if i not in seen:
seen.append(i)
count = val.count(i)
if count > 1:
print(count, "keys have same value of", i)
flag = False

if flag:
print("No keys have same values")

Output

Enter a dictionary D1: {'a': 10, 'b': 20, 'c': 10, 'd': 40, 'e':
10, 'f': 20}
D1 = {'a': 10, 'b': 20, 'c': 10, 'd': 40, 'e': 10, 'f': 20}
3 keys have same value of 10
2 keys have same value of 20

Question 14

Write a program to check if a dictionary is contained in another dictionary e.g., if

d1 = {1:11, 2:12}
d2 = {1:11, 2:12, 3:13, 4:15}

then d1 is contained in d2.


SBOA SCHOOL AND JUNIOR COLLEGE, CHENNAI – 101

Std: XI Computer Science – Dictionary in python


ANSWER

d1 = eval(input("Enter a dictionary d1: "))


d2 = eval(input("Enter a dictionary d2: "))

print("d1 =", d1)


print("d2 =", d2)

if len(d1) > len(d2):


longDict = d1
shortDict = d2
else:
longDict = d2
shortDict = d1

for key in shortDict:


if key in longDict:
if longDict[key] != shortDict[key]:
print("d1 and d2 are different ")
break
else:
print("d1 and d2 are different ")
break
else:
print(shortDict, "is contained in", longDict)

Output
Enter a dictionary d1: {1:11, 2:12}
Enter a dictionary d2: {1:11, 2:12, 3:13, 4:15}
d1 = {1: 11, 2: 12}
d2 = {1: 11, 2: 12, 3: 13, 4: 15}
{1: 11, 2: 12} is contained in {1: 11, 2: 12, 3: 13, 4: 15}

Question 15
A dictionary D1 has values in the form of lists of numbers. Write a program to
create a new dictionary D2 having same keys as D1 but values as the sum of the
list elements e.g.,
D1 = {'A' : [1, 2, 3] , 'B' : [4, 5, 6]}
then
D2 is {'A' :6, 'B' : 15}

ANSWER

D1 = eval(input("Enter a dictionary D1: "))


print("D1 =", D1)
SBOA SCHOOL AND JUNIOR COLLEGE, CHENNAI – 101

Std: XI Computer Science – Dictionary in python


D2 = {}
for key in D1:
num = sum(D1[key])
D2[key] = num
print(D2)

Output
Enter a dictionary D1: {'A' : [1, 2, 3] , 'B' : [4, 5, 6]}
D1 = {'A': [1, 2, 3], 'B': [4, 5, 6]}
{'A': 6, 'B': 15}

Question 16:

Write a program to input your friends’ names and their Phone Numbers and store them
in the dictionary as the key-value pair. Perform the following operations on the
dictionary:
a) Display the name and phone number of all your friends
b) Add a new key-value pair in this dictionary and display the modified dictionary
c) Delete a particular friend from the dictionary
d) Modify the phone number of an existing friend
e) Check if a friend is present in the dictionary or not
f) Display the dictionary in sorted order of names
ANSWER:
dic = {}
#Creates an empty dictionary

#While loop to provide the options repeatedly


#it will exit when the user enters 7
while True:
print("1. Add New Contact")
print("2. Modify Phone Number of Contact")
print("3. Delete a Friend's contact")
print("4. Display all entries")
print("5. Check if a friend is present or not")
print("6. Display in sorted order of names")
print("7. Exit")
inp = int(input("Enter your choice(1-7): "))

#Adding a contact
if(inp == 1):
name = input("Enter your friend name: ")
phonenumber = input("Enter your friend's contact number:
")
dic[name] = phonenumber
SBOA SCHOOL AND JUNIOR COLLEGE, CHENNAI – 101

Std: XI Computer Science – Dictionary in python


print("Contact Added \n\n")
#Modifying a contact if the entered name is present in the
dictionary
elif(inp == 2):
name = input("Enter the name of friend whose number is to
be modified: ")
if(name in dic):
phonenumber = input("Enter the new contact number:
")
dic[name] = phonenumber
print("Contact Modified\n\n")
else:
print("This friend's name is not present in the
contact list")
#Deleting a contact if the entered name is present in the
dictionary
elif(inp == 3):
name = input("Enter the name of friend whose contact is
to be deleted: ")
if(name in dic):
del dic[name]
print("Contact Deleted\n\n")
else:
print("This friend's name is not present in the
contact list")
#Displaying all entries in the dictionary
elif(inp == 4):
print("All entries in the contact")
for a in dic:
print(a,"\t\t",dic[a])
print("\n\n\n")
#Searching a friend name in the dictionary
elif(inp == 5):
name = input("Enter the name of friend to search: ")
if(name in dic):
print("The friend",name,"is present in the list\n\n")
else:
print("The friend",name,"is not present in the
list\n\n")
#Displaying the dictionary in the sorted order of the names
elif(inp == 6):
print("Name\t\t\tContact Number")
for i in sorted(dic.keys()):
print(i,"\t\t\t",dic[i])
print("\n\n")
#Exit the while loop if user enters 7
elif(inp == 7):
break
#Displaying the invalid choice when any other values are
entered
else:
print("Invalid Choice. Please try again\n")
SBOA SCHOOL AND JUNIOR COLLEGE, CHENNAI – 101

Std: XI Computer Science – Dictionary in python

OUTPUT:
1. Add New Contact
2. Modify Phone Number of Contact
3. Delete a Friend's contact
4. Display all entries
5. Check if a friend is present or not
6. Display in sorted order of names
7. Exit
Enter your choice(1-7): 1
Enter your friend name: Mohit
Enter your friend's contact number: 98765*****
Contact Added

1. Add New Contact


2. Modify Phone Number of Contact
3. Delete a Friend's contact
4. Display all entries
5. Check if a friend is present or not
6. Display in sorted order of names
7. Exit
Enter your choice(1-7): 1
Enter your friend name: Mohan
Enter your friend's contact number: 98764*****
Contact Added

1. Add New Contact


2. Modify Phone Number of Contact
3. Delete a Friend's contact
4. Display all entries
5. Check if a friend is present or not
6. Display in sorted order of names
7. Exit
Enter your choice(1-7): 6
Name Contact Number
Mohan 98764*****
Mohit 98765*****

1. Add New Contact


2. Modify Phone Number of Contact
3. Delete a Friend's contact
4. Display all entries
5. Check if a friend is present or not
6. Display in sorted order of names
7. Exit
Enter your choice(1-7): 7

You might also like