Dictionary-Key,Value Pairs
Ques: Write a program to read roll numbers and marks of four students and create a dictionary from it having roll numbers as keys ?
rno = []
mks = []
for a in range(4):
r,m = eval(input("Enter Roll No. , Marks: "))
rno.append(r)
mks.append(m)
d = {rno[0]:mks[0],rno[1]:mks[1],rno[2]:mks[2],rno[3]:mks[3]}
print("Creadted dictionary")
print(d)
Ques: Consider the dictionary created in the previous program. Modify the previous program to check if the roll number2 has scored more than 75 marks ?
rno = []
mks = []
for a in range(4):
r,m = eval(input("Enter Roll No. , Marks: "))
rno.append(r)
mks.append(m)
d = {rno[0]:mks[0],rno[1]:mks[1],rno[2]:mks[2],rno[3]:mks[3]}
print("Creadted dictionary")
print(d)
if d[2] > 75:
print("Roll number 2 scored",d[2],"(>75)")
else:
print("Roll number 2 scored",d[2],"(<75)")
Ques: Write a program to create a phone dictionary for all your friends and print each key value pair in separate lines ?
PhoneDict = {"Madhav":1234567,"Steven":7654321,"Dilpreet":6754321,"Rabiya":4567321,"Murugh an":3215647,"Sampree":4732156}
for name in PhoneDict:
print(name,":",PhoneDict[name])
Ques: Given a dictionary M which stores the marks of the students of class with roll numbers as the keys and marks as the values. Write a program to check if anyone has scored marks as 89.9 ?
M = {1:67.5,2:45.6,3:78.4,4:89.9}
if 89.9 in M.values():
print("Yes,someone has scored 89.9")
else:
print("No one has scored 89.9")
Ques: Write a program to create a dictionary M which store the marks of the students of class with roll numbers as the keys and marks as the values. Get the number of students as input ?
M = {}
n = int(input("How many students ?"))
for a in range(n):
r,m = eval(input("Enter Roll No. , Marks: "))
M[r] = m
print("Created Dictionary")
print(M)
Ques: Consider dictionary M created in the previous example.Write a program to modify the marks of a roll number. Obtai the roll number as input ?
M = {}
n = int(input("How many students ?"))
for a in range(n):
r,m = eval(input("Enter Roll No. , Marks: "))
M[r] = m
print("Created Dictionary")
print(M)
print("To modify marks")
r = int(input("Enter roll number: "))
if r in M:
M[r] = float(input("Enter new marks: "))
else:
print("No such roll number found")
print("Modified Dictionary is")
print(m)
Working with Dictionary
Ques: Write a program to create a dictionary namely Numerals from following two lists ?
keys = ['One','Two','Three']
values = [1,2,3]
Numerals = dict(zip(keys,values))
print("Given two lists are: ",keys,values)
print("Dictionary created with these lists is")
print(Numerals)
Ques: Write a program to add new students' roll number and marks in the dictionary M created with roll numbers as the keys and marks as the values ?
M = {}
n = int(input("How many students ?"))
for a in range(n):
r,m = eval(input("Enter Roll No. , Marks: "))
M[r] = m
print("Created Dictionary")
print(M)
ans = 'y'
while ans == 'y':
print("Enter details of new students")
r,m = eval(input("Enter Roll No. , Marks: "))
M[r] = m
ans = input("More students ? (y/n): ")
print("Dictionary after adding new students")
print(M)
Ques: A Dictionary contains details of two workers with their names as keys and other details in the form of a dictionary as value. Write a program to print the workers' information in records format ?
Employees = {'Jhon':{"age":25,"salary":20000},"Diya":{"age":35,"salary":50000}}
for keys in Employees:
print("Emplyee",keys,':')
print('Age: ',str(Employees[keys]['age']))
print('Salary: ',str(Employees[keys]['salary']))
Ques: Write a program to create a dictionary containing names of competition winners students as keys and numbers of their wins as values ?
n = int(input("How many students ?"))
compwinners = {}
for a in range (n):
key = input("name of the student :")
value = int(input("Number of competetions won: "))
compwinners[key] = value
print("The Dictionary")
print(compwinners)
Ques: Consider already created dictionary M that stores roll numbers and marks. Write a program to input a roll number and delete it from the dictionary. Display an error message if the roll number does not exist in the dictionary ?
M = {}
n = int(input("How many students ?"))
for a in range(n):
r,m = eval(input("Enter Roll No. , Marks: "))
M[r] = m
print("Created Dictionary")
print(M)
rno = int(input("Roll No. to be deleted ? : "))
if rno in M:
del M[rno]
print("Roll No.",rno,"deleted from dictionary.")
else:
print("Roll No.",rno,"does not exist in dictionary.")
print("Final Dictionary")
print(M)
Ques: Program to count the frequency of list of elements using a dictionary ?
import json
sentence = "Coderz*United welcome you to python programing."
words = sentence.split()
d = {}
for one in words:
key = one
if key not in d :
count = words.count(key)
d[key] = count
print("Counting frequencies in list \n",words)
print(json.dumps(d,indent = 1))
Dictionary Function and Methods
Ques: The dictionary M stores the roll_numbers:names of the students who have been selected to participate in national events. Write a program to display the roll numbers selected ?
M = {}
n = int(input("How many students ?"))
for a in range(n):
r,m = eval(input("Enter Roll No. , Marks: "))
M[r] = m
print("Created Dictionary")
print(M)
print("Selected roll numbers are: ")
print(M.keys())
Ques: The dictionary M stores the roll_numbers:names of the students who have been selected to participate in national events. Modify the previous program to display the names of the selected students ?
M = {}
n = int(input("How many students ?"))
for a in range(n):
r,m = eval(input("Enter Roll No. , Marks: "))
M[r] = m
print("Created Dictionary")
print(M)
print("Selected roll numbers are: ")
print(M.values())
Ques: Your school has decided to deposit a scholarship amount of 2500/- to some selected students. Write a program to input the selected students' roll numbers and create a dictionary for the same ?
L = []
n = int(input("How many students ?"))
for a in range(n):
r = int(input("Enter Roll No. "))
L.append(r)
S = dict.fromkeys(L,2500)
print("Created Dictionary")
print(S)
Ques: Write a program to create dictionary with 10 keys 0...9 ?
new_dict = {}
for i in range (10):
new_dict.setdefault(i)
print("Dictionary is")
print(new_dict)
Ques: Write a program to delete the keys of a dictionary, one by one in LIFO order. Make sure that there is no error generated after the last item deleted ?
Stu = {1:'Neha',2:'Saima',3:'Avnit',4:'Ana',5:'Shaji',}
while len(Stu) >= 1 :
print("Element deleted: ", Stu.popitem() )
print("All elements of the dictionary got deleted in LIFO order.")
Ques: Write a program to print the maximum, minimum, sum of keys of numbers dictionary as given below.
numbers = {1:111,2:222,3:333,4:444}
Also individually find minimum, maximum and sum of values ?
numbers = {1:111,2:222,3:333,4:444}
print("Given dictionary is: ",numbers)
max_key_val = max(numbers)
min_key_value = min(numbers)
print("Maximum and minimum keys: ",max_key_val,min_key_value)
max_value = max(numbers.values())
min_value = min(numbers.values())
print("Maximum and minimum values: ",max_value,min_value)
key_sum = sum(numbers)
values_sum = sum(numbers.values)
print("Sum of dictionary's keys: ",key_sum)
print("Sum of dictionary's values: ",values_sum)
NCERT Programs
Ques: Write a Python program to find the highest 2 values in a dictionary ?
numbers = {31:111,22:222,43:333,14:444,25:555}
s = sorted(numbers.values())
print("Given dictiionary is: ",numbers)
print("Heighest two values of given dictionary are :",s[-1],s[-2])
Ques: Write a python program to create a dictionary from a string.
Note. Track the count of letters from the string ?
string = input("Enter a string: ")
d1 = dict.fromkeys(list(string),1)
print("Given string :",string)
print("Dictionary Created: ",d1)
Ques: 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
n = int(input( "How many friends?"))
fd = {}
for i in range(n):
print("Enter details of friend",(i+ 1))
name = input("Name:")
ph = int(input("Phone : "))
fd[name] = ph
print( "Friends dictionary is ", fd)
ch = 0
while ch != 7:
print("\tMenu")
print("1. Display all friends")
print("2. Add new friend")
print("3. Delete a friend")
print("4. Modify a phone number")
print("S. Search for a friend")
print("6. Sort on names")
print("7. Exit")
ch = int(input("Enter your choice (1 - 7) : "))
if ch == 1 :
print(fd)
elif ch == 2:
print( "Enter details of new friend" )
name = input("Name: ")
ph = int(input("Phone :"))
fd[name] = ph
elif ch == 3 :
nm = input("Friend Name to be deleted:")
res= fd.pop(nm, -1)
if res != -1 :
print(res, "deleted")
else:
print("No such friend")
elif ch == 4:
name = input("Friend Name : ")
ph = int(input("changed Phone:"))
fd[name] =- ph
elif ch == 5:
name= input( "Friend Name : ")
if name in fd :
print(name, "exists in the dictionary.")
else:
print(name, "does not exist in the dictionary.")
elif ch == 6:
lst = sorted(fd)
print("{", end = " ")
for a in lst :
print(a, ":", fd[a], end="")
print("}")
elif ch == 7 :
break
else:
print("Valid choices are 1-7 ")