PYTHON PROGRAMS (13.12.
2023)
EXERCISE NO: 04 (OPERATIONS ON DICTIONARY)
CREATING DICTIONARY:
EMPTY DICTIONARY:
Dict1 = { }
print(Dict1)
DICTIONARY WITH KEY:
Dict_Stud = { 'RollNo': '1234', 'Name':'Murali',
'Class':'XII', 'Marks':'451'}
print(Dict_Stud)
DICTIONARY COMPREHENSION:
Dict = { x : 2 * x for x in range(1,10)}
print(Dict)
DICTIONARY METHODS:
dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}
print(dict.keys())
print(dict.items())
print(dict.values())
dict.pop('Marks')
print(dict)
dict_new=dict.copy()
print(dict_new)
dict.clear()
print(dict)
dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}
print('\nName: ', dict.get('Name'))
print('\nAge: ', dict.get('Age'))
dict.update({'Age':22})
print(dict)
ACCESSING ELEMENTS IN DICTIONARY:
MyDict = { 'Reg_No': '1221','Name' : 'Tamilselvi','School' :
'CGHSS','Address' : 'Rotler St., Chennai 112' }
print(MyDict)
print("\nRegister Number: ", MyDict['Reg_No'])
print("Name of the Student: ", MyDict['Name'])
print("School: ", MyDict['School'])
print("Address: ", MyDict['Address'])
ADDING NEW VALUE IN DICTIONARY:
MyDict = { 'Reg_No': '1221',
'Name' : 'Tamilselvi',
'School' : 'CGHSS', 'Address' :
'Rotler St., Chennai 112'}
print(MyDict)
print("\nRegister Number: ", MyDict['Reg_No'])
print("Name of the Student: ", MyDict['Name'])
MyDict['Class'] = 'XII - A' # Adding new value
print("Class: ", MyDict['Class']) # Printing newly added
value
print("School: ", MyDict['School'])
print("Address: ", MyDict['Address'])
DELETING ELEMENTS AND FINALLY THE
DICTIONARY:
Dict = {'Roll No' : 12001, 'SName' : 'Meena', 'Mark1' : 98,
'Marl2' : 86}
print("Dictionary elements before deletion: \n", Dict)
del Dict['Mark1'] # Deleting a particular element
print("Dictionary elements after deletion of a element: \n",
Dict)
Dict.clear() # Deleting all elements
print("Dictionary after deletion of all elements: \n", Dict)
del Dict
print(Dict) # Deleting entire dictionary
BASIC PROGRAMS:
1. ADD NUMBERS IN DICTIONARY:
def returnSum(myDict):
list = []
for i in myDict:
list.append(myDict[i])
final = sum(list)
return final
# Driver Function
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", returnSum(dict))
2. HIGHEST THREE VALUES IN DICTIONARY:
# Python program to demonstrate
# finding 3 highest values in a Dictionary
from collections import Counter
# Initial Dictionary
my_dict = {'A': 67, 'B': 23, 'C': 45,
'D': 56, 'E': 12, 'F': 69}
k = Counter(my_dict)
# Finding 3 highest values
high = k.most_common(3)
print("Initial Dictionary:")
print(my_dict, "\n")
print("Dictionary with 3 highest values:")
print("Keys: Values")
for i in high:
print(i[0]," :",i[1]," ")
3. MULTIPLYING NUMBERS IN DICTIONARY:
# create a dictionary
d={
'value1': 5,
'value2': 4,
'value3': 3,
'value4': 2,
'value5': 1,
}
# create a variable to store result
answer = 1
# run a loop
for i in d:
answer = answer*d[i]
# print answer
print(answer)