Session-8 Dictionary in Python
Session-8 Dictionary in Python
Python Data
Python is a dynamically typed language
Types hence we need not define the type of
the variable while declaring it.
• By giving Key:value pair in the form of separate sequence (By passing tuple of tuple):
>>> dict1 = dict(((‘Amit’,95),(‘Sumit’,’89’),(‘Rumit’,’92’),(‘Punit’,’85’)))
>>> dict1
,'Amit': 95, ‘Sumit': 89, ‘Rumit': 92, ‘Punit': 85}
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
The printing of the dictionary is
same as of the printing of
variables . the print() function is
used to print the dictionary.
Printing
dictionary
Syntax : print(dictionary_name)
>>> dict3*‘Sumit']
89
• Method-1 :
>>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92, • Method 2
‘Punit':85- >>> dict3 = ,‘Amit':95,‘Sumit':89,‘Rumit':92,
>>> for key in dict3: ‘Punit':85-
print(key,':',dict3[key]) >>> for key, value in dict3.items():
print(key,':',value)
Output:
Output:
Amit: 95
Amit: 95
Sumit: 89
Sumit: 89
Rumit: 92
Rumit: 92
Punit: 85
Punit: 85
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
TRAVERSING A DICTIONARY…
To access key and value we need to use keys() and values(). for
example-
Note:- Python raises exception (KeyError) when try to delete a non-existent key.
Note:- del command removes the complete dictionary as an object.
Syntax: del <dictionary_Name>